I'm relatively new in C#, & I'm wondering when to use Delegates appropriately. they are widely used in events declaration, but when should I use them in my own code and why are they useful? why not to use something else?
I'm also wondering when I have to use delegates and I have no other alternative.
Thank you for the help!
EDIT: I think I've found a necessary use of Delegates here
I agree with everything that is said already, just trying to put some other words on it.
A delegate can be seen as a placeholder for a/some method(s).
By defining a delegate, you are saying to the user of your class, "Please feel free to assign, any method that matches this signature, to the delegate and it will be called each time my delegate is called".
Typical use is of course events. All the OnEventX delegate to the methods the user defines.
Delegates are useful to offer to the user of your objects some ability to customize their behavior. Most of the time, you can use other ways to achieve the same purpose and I do not believe you can ever be forced to create delegates. It is just the easiest way in some situations to get the thing done.
Personally, it feels to me that using delegates split up your code into units and make it tons more manageable. Great mechanism to use in conjunction with unit testing if most of your methods have the same signature pattern
"Please feel free to put any method that match this signature here and it will be called each time my delegate is called" -> you made my day, great explanation!
Also consider it as runtime dynamic binding with many of the benefits of compile time static binding. Invocation of a delegate is orders of magnitude faster than the reflection invoke alternative. Additionally if a function signature changes such that it no longer matches the delegate this results in a compile time error which you don't get with reflection invoke. Consider for example the scenario of an MSMQ style message router. The Subscriber message receive functions could simply be stored in a dictionary of message routing key and subscriber delegate pair.
Are delegates considered a form of dependency injection?