Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are delegates null rather than an empty list when there is no subscriber?

Can somebody explain why the .Net framework team decided that a delegate without subscribers should be null instead of an object with an empty InvocationList? I'd like to know the rationale that led to this decision.

void DoSomething()
{
    EventHandler handler = SomeEvent;
    if(handler != null)                   //why is this null-check necessary?
    {
        handler(this, EventArgs.Empty);
    }
}

Thanks

like image 466
Marcel Gosselin Avatar asked Nov 02 '09 03:11

Marcel Gosselin


1 Answers

On the CLR level, delegate fields and event fields are regular field.

Just like string MyField defaults to null and not "", so too Action MyField defaults to null and not an empty Action instance.

like image 131
SLaks Avatar answered Oct 14 '22 09:10

SLaks