Update (thank to commenters): delegate immuntability means that cloning achieves nothing over an assignment.
When one writes:
myDelegate += AHandler
a completely new delegate instance is created and assigned to myDelegate.
Therefore, the code below would work exactly the same without the Clone call.
MulticastDelegate (the underlying type) has a Clone method.
To be able to get to the underlying delegate you might need to avoid the usual helper that the event keyword generates, and manage things directly (custom add and remove accessors).
To show this:
class Program {
public delegate void MyDelegate(string name);
public event MyDelegate EventOne;
public void HandlerOne(string name) {
Console.WriteLine("This is handler one: {0}", name);
}
public void HandlerTwo(string name) {
Console.WriteLine("This is handler two: {0}", name);
}
public void HandlerThree(string name) {
Console.WriteLine("This is handler three: {0}", name);
}
public void Run() {
EventOne += HandlerOne;
EventOne += HandlerTwo;
Console.WriteLine("Before clone");
EventOne("EventOne");
MyDelegate eventTwo = (MyDelegate)EventOne.Clone();
MyDelegate eventTwo = EventOne;
Console.WriteLine("After clonecopy");
EventOne("EventOne");
eventTwo("eventTwo");
Console.WriteLine("Change event one to show it is different");
EventOne += HandlerThree;
EventOne("EventOne");
eventTwo("eventTwo");
}
static void Main(string[] args) {
(new Program()).Run();
}
}