So I’m a little bit confused about delegates in C#…. what do they do and how are they useful? I’ve read a few tutorials, and I don’t really get exactly what they’re supposed to do (everyone relates them to function pointers in C, and I’ve never programmed in C).
So… what do delegates do? What’s a scenario in which I should use them? How would I then use them?
Delegates are sort of like objects that represent a method call. One useful way they can be used are as callbacks. For example, imagine you have a method that does something asynchronous, and you want the caller to be able to specify what they want to happen once it completes (
Actionis a type of delegate):A user of
DoSomethingcan now specify the callback as a parameter:You can also use lamba expressions as a shorter way of writing your delegate:
Callbacks are far from the only use cases for delegates. Hopefully this shows you some of their power: the ability to have code to be executed as a variable.