In .NET, what is a delegate? When would I want to use them? How are they best implemented? What
are the "gotchas"?
Delegates
Requires Free Membership to View
When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to keep you informed on recent service-oriented architecture (SOA) and SOA-related topics such as integration, governance, Web services, Cloud and more.
Hannah Smalltree, Editorial DirectorI'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.
This was first published in June 2003