Chapter 8. Delegates, Lambdas, and Events
WHAT'S IN THIS CHAPTER?
Delegates are the .NET version of addresses to methods. Compare this to C++, where function pointers are nothing more than a pointer to a memory location that are not type-safe. You have no idea what a pointer is really pointing to, and items such as parameters and return types are not known. This is completely different with .NET; delegates are type-safe classes that define the return types and types of parameters. The delegate class not only contains a reference to a method, but can hold references to multiple methods.
Lambda expressions are directly related to delegates. When the parameter is a delegate type, you can use a Lambda expression to implement a method that's referenced from the delegate.
This chapter teaches you the basics of delegates and Lambda expressions, and shows you how to implement methods called by delegates with Lambda expressions. It also demonstrates how .NET uses delegates as the means of implementing events.
Delegates exist for situations in which you want to pass methods around to other methods. To see what that means, consider this line of code:
int i = int.Parse("99");
You are so used to passing data to methods as parameters, as in this example, that you don't consciously think about it, and for this reason the idea of passing methods around instead of data might sound a little strange. However, there are cases in which you have a method that does ...