views:

131

answers:

3

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

+1  A: 

I agree that this can be cumbersome and I personally feel that this was a mistake. I cannot think of any reason why this has to be this way.

Andrew Hare
+7  A: 

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.

SLaks
+2  A: 

See Jon Skeet's answer here for a nice discussion of this. It is even possible to get around having to check against null in C# 2.0.

Matt Davis