Why use EventArgs.Empty instead of null?

2019-02-01 15:59发布

I recall reading, on multiple occasions and in multiple locations, that when firing the typical event:

protected virtual OnSomethingHappened()
{
    this.SomethingHappened(this, EventArgs.Empty);
}

e should be EventArgs.Empty if there are no interesting event args, not null.

I've followed the guidance in my code, but I realized that I'm not clear on why that's the preferred technique. Why does the stated contract prefer EventArgs.Empty over null?

6条回答
▲ chillily
2楼-- · 2019-02-01 16:01

EventArgs.Empty is an instance of the Null object pattern.

Basically, having an object representing "no value" to avoid checking for null when using it.

查看更多
相关推荐>>
3楼-- · 2019-02-01 16:09

I believe EventArgs.Empty is used to maintain the convention of passing an argument with an event, even if none are needed.

Mitchel Sellers posted the other half of my reason halfway through my post: it prevents a null reference exception should a method try and do something with that argument (besides check if it is null).

EventArgs.Empty basically does the work of a globally defined Event Argument with no additional information.

To give a similar example of maintaining a convention, our team uses string.Empty to initialize a string because otherwise different coders might use newString = ""; or newString = " "; or newString = null;, all of which may produce different results for different check conditions.

A (slightly pedantic) reason to use EventArgs.Empty vs new EventArgs() is that the former does not initialize a new EventArgs, saving a slight amount of memory.

查看更多
手持菜刀,她持情操
4楼-- · 2019-02-01 16:17

I used long time "new EventArgs()" instead of "EventArgs.Empty"... I think the important is to pass something that will not cause an Null exception.

查看更多
Juvenile、少年°
5楼-- · 2019-02-01 16:20

from Albahari book: "in order to avoid unnecessarily instantiating an instance of EventArgs."

查看更多
\"骚年 ilove
6楼-- · 2019-02-01 16:24

If you're using a general-purpose method which has the EventHandler signature that's called from any event handler and is passed both the object sender and EventArgs e, it can call e.ToString(), e.g., for logging events, without worrying about a null pointer exception.

查看更多
我想做一个坏孩纸
7楼-- · 2019-02-01 16:26

I believe the reasoning behind the NOT NULL is that when passed as a parameter, it is not expected for the method to need to potentially handle a null reference exception.

If you pass null, and the method tries to do something with e it will get a null reference exception, with EventArgs.Empty it will not.

查看更多
登录 后发表回答