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?
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.).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With