- Introduction
- Reviewing Delegates
- Anonymous Methods Are Inline Delegates
- What the Marketing Material Says
- Summary
Reviewing Delegates
Anonymous methods are a condensed way to declare and use delegates. (If you still have questions about what delegates are, read on. If not, skip to the next section.) Delegates started life in languages that preceded .NET languages, as pointers to function signatures. Remember, everything in computers is really bits and bytes; it's how the bits and bytes are treated that matters. Through the invention of function pointers, it was possible to dynamically assign some future, as-yet-unknown function to the pointer, and events were born.
The basic use of function pointers was that the address of one function could be assigned to a single pointer. To invoke the function through a pointer, programmers checked to determine whether the pointer was not null and then called the function indirectly via the pointer. The check for null was a requirement, and "one pointer to one function" ends up being a limitation.
Retrospectively, delegates are the next evolution of raw function pointers. A delegate is a class that encapsulates the pointer; implicitly, delegates in .NET are multicast delegates. To be a multicast delegate simply means that the "one function to one pointer" limitation is gone, because the multicast delegate class contains a list of pointers. The inclusion of an internal list means that the address of more than one function can be assigned to a single delegate. When the delegate—think "event"—is raised or invoked, all of the internally listed functions are called.
In C#, the addresses of functions are inserted in a list via an overloaded += operator and removed via an overloaded -= operator. C# also supports manually defining add and remove blocks; add and remove are to delegates what get and set are to properties.
In C# 1.0 and C# 1.1, we typically assign instances of delegates to event properties. For example, in WinForms a Button control exposes a Click event. The delegate type of Click is EventHandler. EventHandler is a method that takes object and EventArgs arguments. Hence, we can initialize an EventHandler object with any method matching the delegate EventHandler's signature and assign that delegate to Click. Here's how the code might look:
private void Form1_Load(object sender, EventArgs e) { button1.Click += new EventHandler(OnClick); } private void OnClick(object sender, EventArgs e) { Debug.WriteLine("button1 clicked"); }
Because the forms designer for WinForms and the page designer for WebForms automatically add the code for delegate binding, it's possible to write a lot of code without binding delegates manually.