What happens when I add a method to existing delegate? I mean when I added the method1 to del, del holds the address of method1. When I add method2 afterwards, del still points to Method1 and Method 2 address is inserted on the bottom of it. Doesn't this mean I changed the delegate? If I can change this why in the books it is told "delegates are immutable" ?
MyDel del = method1;
del += method2;
del += method3;
You're not changing the Delegate
object - you're changing del
to refer to a different object.
It's exactly the same as with strings. Let's convert your code into the same thing but with strings:
string str = "x";
str += "y";
str += "z";
You end up with str
referring to a string object with contents "xyz"
. But you haven't modified the string objects with contents "x"
, "y"
or "z"
.
So it is with delegates.
del += method2;
is equivalent to:
del = del + method2;
which is equivalent to:
del = (MyDel) Delegate.Combine(del, method2);
In other words, "create a new delegate object which has invocation lists referring to the existing two delegate objects". (If either del
or method2
is null, it doesn't need to create a new object.)
See Delegate.Combine
for more details.
See more on this question at Stackoverflow