Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
Hi All,
I have some confusion on Multicast Delegate(in C#),

when the multicast delegate is called, it invokes the

method and should the method must void? I can't find

any official document.

Please give me a hand and thanks a lot.

You can check the example the link as below.

http://msdn.microsoft.com/zh-cn/library/ms173175.aspx
Posted
Updated 23-Apr-11 5:34am

In general, it's a good practice to use delegates with void return types. Otherwise when you have a multicast delegate the return value is unpredictable because the order of delegate invocation is not guaranteed.
 
Share this answer
 
Comments
Richard MacCutchan 23-Apr-11 11:38am    
A nice, clear, simple answer that tells us everything we need to know: +5.
Nish Nishant 23-Apr-11 11:38am    
Thanks Richard!
Sergey Alexandrovich Kryukov 23-Apr-11 22:22pm    
Nishant, this is a prudent advice for those who wants to do just the basics -- my 5.
For crazy people like myself there is an advanced use (I used it for quite a practical purposes).
For this advanced use, return value does make sense.
Please see my answer and code sample.
--SA
ThatsAlok 18-Dec-13 1:54am    
better to put parameter as reference, if you want to return values from multicast delegate
Sergey Alexandrovich Kryukov 18-Dec-13 3:11am    
Why?! I don't see any benefits of it. Can you explain in detail?
—SA
You can only use return type of the delegate if you do not invoke the delegate, but manually call each handler from the invocation list of the delegate invocation list. Here is the example on how to do it:

C#
delegate int NonVoidDelegate(string parameter);

//...


NonVoidDelegate delegateInstance = delegate(string parameter) { return 1; };
delegateInstance += delegate(string parameter) { return 2; };
delegateInstance += delegate(string parameter) { return 3; };

var list = delegateInstance.GetInvocationList();

foreach (var handler in list) {
   NonVoidDelegate method = (NonVoidDelegate)handler;
   int retValue = method("some parameter");
   //do something with retValue...
}


—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900