#374 – A Custom Delegate Derives from System.MulticastDelegate

You define a new delegate in C# using the delegate keyword.

        private delegate void StringHandlerDelegate(string s);

This is equivalent to defining a new class that inherits from System.MulticastDelegate (which in turn inherits from System.Delegate).  MulticastDelegate is a class that knows how to refer to a set of methods–known as as the delegates invocation list.

Later in your code, you declare an instance of your delegate and set it equal to a method.

            StringHandlerDelegate del = Method1;

When you do this, you’re creating an instance of the new MulticastDelegate subclass and giving it a reference to the Method1 method.

You can also add a second method to the invocation list using the += operator.

            del += Method2;

At this point, a new delegate is created and System.Delegate.Combine method is then called to combine the two delegates into a new delegate that points to both methods.

Advertisements

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

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 )

w

Connecting to %s

%d bloggers like this: