Why does C# require you to write a null check ever

2020-02-05 11:56发布

This seems odd to me -- VB.NET handles the null check implicitly via its RaiseEvent keyword. It seems to raise the amount of boilerplate around events considerably and I don't see what benefit it provides.

I'm sure the language designers had a good reason to do this.. but I'm curious if anyone knows why.

标签: c# events null
9条回答
祖国的老花朵
2楼-- · 2020-02-05 12:53

You need to consider what code would be required if setting up the plumbing to raise the event in the first place would be expensive (like SystemEvents) or when preparing the event arguments would be expensive (like the Paint event).

The Visual Basic style of event handling doesn't let you postpone the cost of supporting such an event. You cannot override the add/remove accessors to delay putting the expensive plumbing in place. And you cannot discover that there might not be any event handlers subscribed so that burning the cycles to prepare the event arguments is a waste of time.

Not an issue in C#. Classic trade-off between convenience and control.

查看更多
Bombasti
3楼-- · 2020-02-05 12:57

The reason really boils down to C# giving you more control. In C# you do not have to do the null check if you so choose. In the following code MyEvent can never be null so why bother doing the check?

public class EventTest
{
  private event EventHandler MyEvent = delegate { Console.WriteLine("Hello World"); }

  public void Test()
  {
    MyEvent(this, new EventArgs());
  }
}
查看更多
来,给爷笑一个
4楼-- · 2020-02-05 13:00

Don't really know why is this done, but there's a variation of a Null Object pattern specifically for delegates:

private event EventHandler Foo = (sender, args) => {};

This way you can freely invoke Foo without ever checking for null.

查看更多
登录 后发表回答