#373 – A Delegate Can Refer to More than One Method

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.

Advertisements