Search code examples
c#delegatesreference-type

Doesn't delegate type act like other reference types when assigning happens?


Why doesn't the following code behave as the other reference types in the very situation which is when we assign a ref object to another ref object, both objects will point to the same location in the memory? It look likes a copy by value happened here to me.

delegate declaration:

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

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

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

The output:

Printing from PrintText1: Hello
Printing from PrintText2: Hello


Solution

  • Delegates are immutable, so when you run e.g. this line (which calls Delegate.Remove):

    carHandler2 -= PrintText2;
    

    you create a new delegate and store it in carHandler2 instead of changing the existing one.


    To illustrate this more, take a look at the following code, which uses strings (strings are also a reference types and immutable):

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

    string2 is now FooBarEvenMorebar, but string1 is still FooBar.