C# language: 15. Events and delegates

Delegates are often compared to indicators in functions in C or C ++, while it is necessary to remember about many rules at the pointers, using delegates is much simpler.

For example, if you want a user to enter a value of 1 or 0 when you enter 1, you will see an inscription on the screen “Binary one” and when 0 “Binary zero” of course, you can use the if statement but for larger projects the delegates are more practical.

Construction of a delegate

That’s how the delegates are created, just add a delegate, like a method only without a body. Example:

Let’s create a program in the Main function, which we described at the beginning of the lesson, it will look like this:

And what do we have here? First, we created a delegate then its object in the Main function, then we retrieve data from the user and depending on what the user have written, we saving the appropriate method to the delegate, then we call the delegate.

And now let’s create more methods in the Main function:

And let’s add this function to the delegate and call it:

This is whole sense of the delegates, if we want to call a larger number of functions, we can just use the delegate.


Events are very connected with delegates, they are used during the program operation, eg in WPF, what do you think about why a specific method is called after clicking a button?

Let’s look at the method of calling the button event:

This is the button click event.

Now let’s see how events work with delegates in the console.

The most important in this is that the event is called in the class EventClass and the arguments are passed to the delegate in the Main function and displayed in the console. Below the result:

This content also you can find on my steemit blog: https://steemit.com/programming/@slawas/c-language-15-events-and-delegates

And on medium: https://medium.com/@sawomirkowalski/c-language-15-events-and-delegates-be1e6f966922

That’s all in the next lesson will be dictionaries, see you!

If that post was useful for you share it with your friends :)

Post a comment

Notify about