C# Delegates and Events—Multicast delegates
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
|
| edit |
Multicast delegates
As I said in the introduction, delegates do far more than provide an indirect way to call a method. They also contain an internal list of delegates—called the invocation list—which contains delegates of the same method signature. Whenever the delegate is invoked, it also invokes each delegate in its invocation list. You add and remove delegates from an invocation list using the overloaded += and -= operators.
The next example defines two methods of the correct signature for our GreetingDelegate and calls them both through a single call to an instance of the GreetingDelegate.
class Greeting { public void SendGreeting(string s) { Console.WriteLine(s); } public void SendGreetingToFile(string s) { StreamWriter writer = new StreamWriter(@"c:\greeting.txt"); writer.WriteLine(s); writer.Close(); } } class DelegateDemo1 { static void Main(string[] args) { // create the Greeting object Greeting gr = new Greeting(); // create the delegates GreetingDelegate gd = new GreetingDelegate(gr.SendGreeting); gd += new GreetingDelegate(gr.SendGreetingToFile); // invoke both methods through the delegate gd("Hello"); } }
In this example, we have added a second method to the Greeting class. The SendGreetingToFile method does exactly as its name suggests. It creates a StreamWriter instance and uses it to log the string argument to a file named "greeting.txt".
This time, after creating the GreetingDelegate, the Main method instantiates a second GreetingDelegate and appends it to the first instances’ invocation list through the += operator. When the last line of Main calls the delegate, both methods are invoked with the string “Hello”.
So far, we have seen delegates used to call methods of other classes and objects. But, as I have already said, that is only the beginning. The fact that they can be bound to methods of any class or object gives them great utility. Delegates are central to .NET, as they are used in threads, events, and asynchronous programming. Now that we have seen how to create and use delegates, let’s take a look at some of their applications.
|

