Delegates are immutable, but how?

What happens when I add an existing delegate method? I mean, when I added method1 to del, del stores the address of method1. When I add method2 after this, del still points to method 1, and the address of method 2 is inserted at the bottom. Doesn't that mean that I changed the delegate? If I can change this, then why do the books say "delegates are immutable"?

MyDel del = method1; del += method2; del += method3; 
+5
source share
4 answers

Let me use a simple analogy. int is immutable, so when you put

 int x = 123; x += 1; 

really mean

 int _x = x + 1; x = _x; 

when you add one, you get a new temporary variable _x , and then discard the initial x , substituting it for _x ; in case of delegates

 del += method2; 

means the same:

 delegate _del = delegate.Combine(del, method2); del = (MyDel) _del; 
+5
source

You do not change the Delegate object - you change del to refer to another object.

This is exactly the same as with strings. Let me convert your code to the same thing, but with the lines:

 string str = "x"; str += "y"; str += "z"; 

You end up with str referring to a string object with the contents of "xyz" . But you did not change the string objects with the contents of "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 that has call lists that reference the existing two delegate objects." (If either del or method2 is null, it does not need to create a new object.)

See Delegate.Combine more details.

+8
source
 del += method2; 

The compiler turns this into something like:

 del = (MyDel)Delegate.Combine(del, method2); 

As you can see, the new delegate is obtained from the original and additional (both of which remain unchanged), then the result is reassigned to the original delegate variable. (Only the delegate object is immutable, not the variable / field referencing it.)

Related question: How does the + operator work to combine delegates?

+3
source

And another version in other words:

 MyDelegate delegateOriginal = Method1; MyDelegate copyOfOriginal = delegateOriginal; Object.ReferenceEquals(printAllhandler, anotherHandler); // return true 

Returns true because the delegateOriginal and copyOfOriginal refer to the same instance.

Then

 delegateOriginal += Method2; 

If the delegate was changed with the following expression, then true will be returned, since the variables will refer to the same object, but:

 Object.ReferenceEquals(printAllhandler, anotherHandler); // return false 

Because delegate is immutable.
String delegateOriginal += Method2; will create a new instance of the delegate and place a link to the source variable.

+2
source

Source: https://habr.com/ru/post/1259452/


All Articles