#373 – A Delegate Can Refer to More than One Method
July 22, 2011 3 Comments
An instance of a delegate can refer to a method. In C#, delegate types created using the delegate keyword are multicast–they can refer to more than one method at the same time.
In the example below, we define a new delegate type, StringHandlerDelegate, that can refer to a method that has a single string parameter and no return value. We then declare an instance of that delegate and set it to refer to the Method1 method. Finally, we use the += operator to indicate that the delegate instance should also refer to the Method2 method.
private delegate void StringHandlerDelegate(string s); static void Main() { StringHandlerDelegate del = Method1; del += Method2; // Invoke via the delegate--both methods are called del("Snidely Whiplash"); } static void Method1(string text) { Console.WriteLine(text); } static void Method2(string name) { Console.WriteLine("Your name is {0}", name); }
When we invoke the delegate, both methods are called.
Pingback: #385 – A Delegate Instance Can Refer to Both Instance and Static Methods « 2,000 Things You Should Know About C#
Pingback: #551 – Use Anonymous Method When Adding to an Invocation List « 2,000 Things You Should Know About C#
Pingback: #1,021 – What Happens to a Delegate’s Return Value | 2,000 Things You Should Know About C#