#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Pingback: #385 – A Delegate Instance Can Refer to Both Instance and Static Methods « 2,000 Things You Should Know About C#

  2. Pingback: #551 – Use Anonymous Method When Adding to an Invocation List « 2,000 Things You Should Know About C#

  3. Pingback: #1,021 – What Happens to a Delegate’s Return Value | 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: