开发者

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 subscribe开发者_如何学编程rs 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


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.


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.


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.


Using null to handle an empty list is efficient at run-time, especially since the vast majority of events have either zero or one subscribers. The defect in C# is not the use of null to handle an empty list, but rather the fact that in many contexts the event name refers to the delegate rather than the event. A better design would have named the delegate with a preceding underscore or other prefix, and then only allowed particular operations with the event name:

  1. Subscription
  2. Unsubscription
  3. Invocation (should invoke _eventName if non-null, else do nothing)

For all other event operations, one would have to use _eventName. Such a design would have saved countless thousands (if not millions) of lines of code, as compared with requiring user code to copy the event delegate, test if null, and invoke the copy if not.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜