I have gone through many articles but I am still not clear about the difference between the normal delegates that we usually create and multicast delegates.
public delegate void MyMethodHandler(object sender);
MyMethodHandler handler = new MyMethodHandler(Method1);
handler += Method2;
handler(someObject);
The above delegate MyMethodHandler will call these two methods. Now where does multicast delegates come in. I have read that they can call multiple methods but I am afraid that my basic understanding about delegates is not correct.
To clarify a bit: All delegates are instances of the class
MulticastDelegate
, regardless of whether they have one or multiple target methods. In principle there are no difference between a delegate with a single or multiple targets, although the runtime is optimized a bit towards the common case with a single target. (A delegate with 0 targets is not possible though, it is one or more.)When you are instantiating a delegate like
new MyMethodHandler(Method1)
, you create a delegate with a single target (theMethod1
method).Delegates with multiple targets are created by combining two existing delegates. The resulting delegate will have the sum of targets. Delegates can be combined explicitly with
Delegate.Combine()
, but also implicitly by using the+=
operator on an existing delegate, as in your example.Invoking a delegate in turn calls every target in the delegate. So in your example
handler(someObject);
will call two methods (Method1
andMethod2
), since you have created a delegate with these two targets.The C# specification states that all delegate types must be convertible to
System.Delegate
. In fact the way the implementation implements this is that all delegate types are derived fromSystem.MulticastDelegate
, which in turn derives fromSystem.Delegate
.Is that clear? I'm not sure that answered your question.
Sorry for adding to somebody else's answer but I thought that delegates are called in the order they are added.
"Multicast Delegates" section
http://msdn.microsoft.com/en-us/library/orm-9780596527570-03-04.aspx
A multicast delegate is a delegate that has references to more than one function. When you invoke a multicast delegate, all the functions the delegate is pointing to, are invoked.
Type 1:
0 argument and void return type delegate -
Method 1 -
Method 2 -
Type 2:
0 arguments and int return type delegate
Method 1-
Method 2-
Same process as Type 1
So when there is a return type of a MultiCast Delegate the return value is the return value of last delegate.
Type 3:
int, int, ref int arguments and void return type delegate -
"All delegate instances have multicast capability." - http://msdn.microsoft.com/en-us/library/orm-9780596527570-03-04.aspx
"In C#, all delegate types support multicast" - http://msdn.microsoft.com/en-us/library/orm-9780596516109-03-09.aspx
This article explains it pretty well: