Delegates

mp3909

Well-known member
Joined
Apr 22, 2018
Messages
61
Location
UK
Programming Experience
3-5
So, I read up on delegates and I am still confused why do we need them in C#?
I mean, what's the point of calling a method indirectly through the use of a delegate when you can call that same method directly?

I am failing to understand the essence of delegates and was hoping someone can give me a real example of their use?

Thanks!
 
what's the point of calling a method indirectly through the use of a delegate when you can call that same method directly?
Because there are times that you simply can't call the same method directly. Generally speaking, delegates are used when you know what method needs to be invoked in one place in your code but you want to invoke it somewhere else. You create the delegate in the first place and then invoke it in the second. With regards to JohnH's example, If you want to use a method that you write in your own application to compare instances of a class that you wrote for the purposes of sorting, it should be obvious that the List<T> class couldn't possibly call your method directly because, when the authors wrote that class, they had no idea that you existed, never mind your method.

Probably the most common use for delegates is event handlers. Let's say that you write a method that you want executed when the user clicks a Button so you register that method as a handler for the Click event of that Button. Have you ever wondered what that actually means? An event is really just a collection of delegates. Registering a method as a handler for an event means creating a delegate for that method and adding it to the collection. When the user clicks the Button in the UI, the Button class loops through that collection of delegates and invokes each one. As per my initial description, you know what method you want invoked when you write your form code but the method needs to be invoked from inside the Button class, so you create a delegate for your method and pass it to the Button instance. That's exactly what code like this does:
C#:
button1.Click += button1_Click;
 
Back
Top Bottom