Click here to Skip to main content
15,887,273 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Could anyone tell how does multicast delegate execute?


I am very confused in delegates working.


Please help me in this by giving any live example or code.



Thanks
Seema
Posted

 
Share this answer
 
v3
Comments
Wendelius 21-Aug-12 17:55pm    
Good links, 5
Prasad_Kulkarni 22-Aug-12 0:00am    
Thank you Mika!
This is not very simple to explain, and the Microsoft documentation, quite clear and comprehensive on most cases, keeps silence about most aspects of delegates. Nevertheless, please read all this documentation before reading my answer, because this matter is pretty hard to understand.

First thing to understand is: delegates as types and delegate instances (members of a class/structure) are not related in the same way as classes and instances. The run-time type of the delegate instance have nothing to do with delegate type (!). With Reflection, you can examine any instance and see that its type is some class. And a delegate type is not.

Second confusing thing is the multicast. Actually, what happen is: you declare a delegate instance, and it's always null. Amazingly, you can add a handler the its invocation list using "+=" operator. This is the moment when a delegate instance is actually initialized (another way is to assign one instance to another to get to references referencing the same delegate instance, but this way you don't create any instances; there are no other ways). This delegate appears to be single-case. You can add one more handler to it. It will always work. Not attention! You will get multcast delegate instance now (with two elements in its invocation list). But this is always a brand new instance not the same as the previous instance. You can easily check it when you compare them referentially. When you add one more handler, you get a multicast instance again (of course, 3 handler), but this is a brand new instance again! The delegate instances are immutable. Why? The answer is: multithreading.

There are some other wonderful facts about the delegates.

I described some more detail in my article: Dynamic Method Dispatcher[^], please see the section "4.1. On the Nature of Delegate Instance".

Your follow-up questions are welcome.

—SA
 
Share this answer
 
Comments
Wendelius 21-Aug-12 17:54pm    
My 5
Sergey Alexandrovich Kryukov 21-Aug-12 18:05pm    
Thank you, Mika.
--SA

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