4

I have a pretty basic event:

public event EventHandler OnAborted;

All I need to do is call this event, I don't even need to provide any arguments, so it's nothing fancy. I'm confused with the correct usage of the EventArgs argument.

I can use:

if (OnAborted != null)
   OnAborted(this, EventArgs.Empty);

Or I can even use:

if (OnAborted != null)
   OnAborted(this, new EventArgs());

In both cases, EventArgs seems to be pretty useless, I can't even provide any arguments (not that I need to, but that's not the point).

What is the proper usage of EventArgs? Should I create a custom class that inherits EventArgs?

Mike Eason
  • 9,525
  • 2
  • 38
  • 63
  • 2
    If you're not passing any data, then just use `EventArgs.Empty`. The advantage `EventArgs.Empty` has over `new EventArgs` is that it doesn't needlessly allocate and create a new object on the heap. – Dai Mar 16 '15 at 09:30
  • @Dai That's useful to know, thanks. Does EventArgs have any other purpose besides being a base class for custom EventArgs? – Mike Eason Mar 16 '15 at 09:39

1 Answers1

2

Using EventArgs.Empty does not create a new object and allocates it on the heap. More over, EventArgs.Empty is an instance of the Null Object Pattern. Having an object representing "no value" to avoid checking for null when using it.

To add more to when you should use EventArgs or your proper class, here you have some MSDN guideline on Event Design :

Consider using a derived class of System.EventArgs as the event argument, unless you are absolutely sure the event will never need to carry any data to the event-handling method, in which case you can use the System.EventArgs type directly.

If you define an event that takes an EventArgs instance instead of a derived class that you define, you cannot add data to the event in later versions. For that reason, it is preferable to create an empty derived class of EventArgs. This allows you add data to the event in later versions without introducing breaking changes.

Community
  • 1
  • 1
Tomasz Jaskuλa
  • 15,723
  • 5
  • 46
  • 73