Consider the following demo
class Program
{
static void Main(string[] args)
{
MyCallBackClass myCallbackInstance = new MyCallBackClass();
MyDelegate myDelegate = delegate() { /*Do nothing*/ };
myDelegate += () => { Console.WriteLine("First"); };
myDelegate += () => { Console.WriteLine("Second"); };
myCallbackInstance.Callback = myDelegate;
myDelegate += () => { Console.WriteLine("Third"); };
myCallbackInstance.InvokeCallback();
Console.ReadLine();
}
}
delegate void MyDelegate();
class MyCallBackClass
{
public MyDelegate Callback { get; set; }
public void InvokeCallback()
{
if (Callback != null)
Callback();
}
}
Since a delegate is a reference type in C#, as read here Why are delegates reference types? I would expect the reference to the delegate ("Callback") in my object to point to the same delegate as the reference outside of the object ("myDelegate"). Much to my surprise, the output of this demo application is:
First
Second
, the third element added to the delegate (MulticastDelegate) is not invoked by the object.
This is not the behaviour I expect from reference types and it seems to me that the delegate is handled as if it were a value type. Where am I wrong in my assumptions? Why isn't the third delegate-element invoked?