Delegates and Events
Callback functions are an important part of programming in Windows. If you have a background in C or C++ programming, you have seen callbacks used in many of the Windows APIs. With the addition of the AddressOf keyword, Visual Basic developers are now able to take advantage of the API that once was off limits. Callback functions are really pointers to a method call. Also known as function pointers, they are a very powerful programming feature. .NET has implemented the concept of a function pointer in the form of delegates. What makes them special is that, unlike the C function pointer, the .NET delegate is type-safe. What this means is that a function pointer in C is nothing but a pointer to a memory location. You have no idea what that pointer is really pointing to. Things like parameters and return types are not known. As you see in this chapter, .NET has made delegates a type-safe operation. Later in the chapter, you see how .NET uses delegates as the means of implementing events.
The main topics of this chapter are:
- Anonymous methods
- Lambda expressions
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 ...