#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.

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

Leave a comment