Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegates are immutable but how?

Tags:

c#

delegates

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;
like image 974
Lyrk Avatar asked Nov 08 '16 09:11

Lyrk


2 Answers

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.

like image 157
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet


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;
like image 22
Dmitry Bychenko Avatar answered Nov 14 '22 22:11

Dmitry Bychenko