Methods are delegate types. It is that simple. Since delegates are types in .NET we can use any method as types, that means we can pass methods as parameters and we can return methods.
The below code shows different ways we can instantiate a delegate.
A delegate has different ways of invocation. The very direct way is calling the delegate itself with the parameters. This indirectly invokes the Invoke() method of the delegate. Invoke() is generated by the compiler with the correct parameter list.
The following code shows the direct invocation.
Other way of handling a delegate invocation is, invoking the method asynchronously. BeginInvoke() and EndInvoke() of a delegate is used for this.
BeginInvoke() is generated for a delegate with that specific delegate’s parameters as first set of parameters, next parameter is a AsyncCallback type method and last one is a object which could have values to the callback method.
The following code explains how to use the BeginInvoke() and EndInvoke() to asynchronous execution.
If the method hasn’t finished the execution when the EndInvoke() is called, the callback method waits till the execution is finished.
Another way of invoking a delegate is by using its DynamicInvoke(). More often this is direct as Invoke(), but has the difference in the parameters passed to the delegate. DynamicInvoke() has a object array parameter. We should pass the parameters with the correct data types and it should be with the correct parameter count. If the parameter is not correct it will throw an ArgumentException and if the number of parameters doesn’t match it will throw TargetParameterCountException.