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.
Let me use a simple analogy. int
is immutable, so when you put
int x = 123;
x += 1;
it actually means
int _x = x + 1;
x = _x;
when adding one you get a new temporary variable _x
and then drop initial x
by substituting it with _x
; in case of delegates
del += method2;
means quite the same:
delegate _del = delegate.Combine(del, method2);
del = (MyDel) _del;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With