Summary

A delegate is useful in order to encapsulate a method. It is like any data type in C# in which a variable can be initialized to have the delegate data type. Since it similar to data types, increment and decrement operations can be applied to the delegate, making it possible to create a multicast delegate from several delegates. However, one thing to remember, since the Delegate.Combine() and Delegate.Remove() methods return the Delegate data type, is that we have to cast the return of both methods to the expected instance delegate when using them. Compared to the += and -= operators use, however, since they are implemented at the language level in the compiler and the delegate type is known, there's no need to cast the result of the increment and decrement delegate operation.

C# also has built-in delegates, Action and Func, which make the code shorter, and the definition of the delegate becomes easier and quicker. As a result, the code gets simpler to be analyzed. Also, there are two variances in the use of delegates; covariance and contravariance, which will allow us to assign a method to the delegate. Covariance allows a method to have a return type that is more derived than the return type that is defined in the delegate, while contravariance allows a method to have the parameter types that are less derived than the parameter types that are defined in the delegate.

We now have a better understanding about delegates. Let's move on to the next chapter, where we are going to leverage the power of delegates to express anonymous methods using the lambda expression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset