Today we are going to add a new weapon to our arsenal called delegates, C# really provides interesting ways to do programming and delegates are a good example of it. So, let us study what delegates are and how they can make our programming experience more productive and make our code cleaner.
What is Delegate?
A delegate is a type that represents, reference to method with a particular return type and parameter list, and this reference can be changed dynamically. In other words, it is a pointer to function that matches signature with it
i.e. return type and parameter list.
When to use Delegates?
Sometimes, we need to programmatically change the method that is called or we need to pass functions as a parameter to another function, or we need to implement callback function, or we need to implement an event. In all cases, we can effectively make use of delegates.
How to create Delegate?
delegate <return type> <delegate-name> (<parameter list>);
delegate int <delegate-name>(int x, int y)
<delegate-name> sampleDelegate = new <delegate-name>(<method_name_having_two_int_parameters_and_returning_int_value>);
int retValue = sampleDelegate(10, 20);
When we create an instance of a delegate we can associate it with one or more than one functions which match its signature, all of them will be called. The method we wish to attach to delegate need not be of the same class or struct it can be any method accessible over there, it may be an instance method or static also, as a result of this we can plug new functionality to existing classes also.