Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use EventArgs.Empty instead of null?

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?

like image 365
Greg D Avatar asked Oct 09 '08 19:10

Greg D


People also ask

Can EventArgs be null?

EventArgs is a reference type and there's no protection in C# against null values on reference types. CA1062 is generic warning, you can disable/ignore it in case you never pass null (because you can subclass form and rise event yourself, etc.).

What does EventArgs mean?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information. Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event. Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx.

Why is my event handler null?

The event handler will be null unless somebody has subscribed to the event. As soon as a delegate is subscribed to the event, it will no longer be null. This protects you from a null exception if there has been no subscribers.


2 Answers

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.

like image 167
Mitchel Sellers Avatar answered Oct 20 '22 12:10

Mitchel Sellers


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.

like image 42
Martin Konicek Avatar answered Oct 20 '22 11:10

Martin Konicek