Lyrk Lyrk - 1 month ago 21
C# Question

Delegates are immutable but how?

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;

Answer

Let't 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;