Does the type delegate to act like other reference types when assigned?

Why does the following code not behave like other reference types in the situation when we assign the ref object to another ref object, both objects point to the same place in memory? It seems to me that I liked the copy by value.

delegate Announcement:

class Car {
   public delegate void CarEngineHandler(string text); 
   /* ... */
}

Car.CarEngineHandler carHandler1 = PrintText1;
carHandler1 += PrintText2;

Car.CarEngineHandler carHandler2 = carHandler1;
carHandler2 -= PrintText2;
carHandler1("Hello");

Output:

Printing from PrintText1: Hello Printing from PrintText2: Hello

+4
source share
1 answer

Delegates are immutable, so when you run, for example, this line (which calls Delegate.Remove):

carHandler2 -= PrintText2;

you create a new delegate and save it in carHandler2instead of modifying the existing one.


, , ( ):

String string1 = "Foo";
string1 += "Bar";
String string2 = string1;
string2 += "EvenMorebar";

string2 FooBarEvenMorebar, string1 - FooBar.

+4

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


All Articles