In .NET, what is a delegate? When would I want to use them? How are they best implemented? What are the "gotchas"?...
Delegates are fun. If you've been programming for any length of time, you've been introduced to the concept of delegates as function pointers. As a quick review, pointers are used to store the address of a thing. By changing the address contained in a pointer, the same pointer can reference multiple things during the course of execution of a program. Thus, a pointer named "stackTop" can point to an infinite number of things as they are pushed and popped from a stack implementation. We are most familiar with pointers pointing to pieces of information. However, since pointers just store addresses under the covers, they can point to other program data as well. In particular a pointer can store the location of a function entry point and a programmer can use the pointer to instruct a computer to execute at the location stored in the pointer. Typically, the role of telling the computer how to hop around is relegated to the compiler and all the jumps are determined before the program starts running. However, it is sometimes not possible to know all the jumps when a program is compiled and the jumps need to be determined by a program as it executes. This is where we typically use function pointers. I've said more about pointers than most folks need, I'm sure. Delegates behave similarly to function pointers in C and C++. In C a programmer can create a type-safe pointer to a function and store those pointers just like any other pointer. These pointers can be assigned and later used to call the functions they reference. In C++ and other object languages, things get a bit more tricky. In object-oriented languages, most function processing is done in the context of an object instance (method call). Consider the case where a class implements a generic print function that takes no arguments and returns void. Let's consider further that calling the print function on an object instance emits the object's state information to the console. Now let's consider that we create a pointer to the print function where the pointer's definition is "a function that takes no arguments and returns void"... The rest of this response is posted in our .NET Developer Tips. Click here to read the rest, which includes some sample code.
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.