Thursday, January 28, 2010

Multicast Delegates C# an Example

The C# language has a feature known as the multicast delegate. Any delegate that has a void return type, is a multicast delegate. A multicast delegate can be assigned and invoke multiple methods.

You may have seen hints of this in your code. For example, if you are doing ASP.NET development and have ever looked at a page's InitializeComponent() method, you may have noticed a statement like this:

this.SearchButton.Click += new System.EventHandler(this.SearchButton_Click);

Notice the += in that statement. That is a clue. You could add another event handler if you wanted, and it would get called as well. For example, let's say you wanted to also call a method named NotifyStatistics every time the Search button was clicked. Then your code could be:

this.SearchButton.Click += new System.EventHandler(this.SearchButton_Click);
this.SearchButton.Click += new System.EventHandler(this.NotifyStatistics);

Every time the user clicks the Search button, first SearchButton_Click() is called, followed by NotifyStatistics(). The event handlers are called in the order they are added. Likewise, using -=, an event handler can be removed.