Chapter 6. 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.

Delegates

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, 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 something, and rather ...

Get Professional C# 2005 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.