Here is the code which defines a C# EventHandler, as written in the documentation, it represents the method that will handle an event that has no event data:

// Summary:
//     Represents the method that will handle an event that has no event data.
//
// Parameters:
//   sender:
//     The source of the event.
//
//   e:
//     An System.EventArgs that contains no event data.
[Serializable]
[ComVisible(true)]
public delegate void EventHandler(object sender, EventArgs e);

So after declaring a specific event:

private event EventHandler OnSomethingHappened;

We need to write a method to raise this event:

private void RaiseOnSomethingHappened()
{
    if (OnSomethingHappened != null)
    {
        OnSomethingHappened(this, new EventArgs());
    }
}

There is another way to raise events, read about it in A New Pattern For Event Declaration. Anyway, we can define EventArgs as a private member and use it instead of allocating an EventArgs object every time the event is raised. Fortunately, there is no need for that, C# introduce us the EventArgs.Empty! So, this code should look like this:

private void RaiseOnSomethingHappened()
{
    if (OnSomethingHappened != null)
    {
        OnSomethingHappened(this, EventArgs.Empty);
    }
}

I have to admit that I had a lot of thoughts wether to write this post or not. I was pretty sure that most of the developers know about that issue and I will only tell the obvious. But after doing a little research, I found out that ~40% of my colleagues didn’t use EventArgs.Empty so I realized that it might be new to some of Dev102 readers too. Please be honest, were you aware of this issue or not?

Tags :

7 Responses to “EventArgs.Empty – Do You Use It?”


  1. JOHN

    Said on September 22, 2008 :

    To be honest, whenever I need empty args, I just pass a null.

    Works for me.

  2. Matti Lehtinen

    Said on September 23, 2008 :

    Great tip! I have always used new EventArgs() without knowing there is a better alternative.

  3. sirrocco

    Said on September 23, 2008 :

    I know about the EventArgs.Empty … but I find myself using it on and off.

    PS : it depends on – I have no idea what :)

  4. Rinat Abdullin

    Said on September 23, 2008 :

  5. Andrei Rinea

    Said on September 23, 2008 :

    I hope I will be believed but I knew about EventArgs.Empty and used it. Although I didn’t find out about it by careful study but Intellisense exploration ( LOLz ) and studying source code from others.

    I guess it’s safer than null because you can ellimiate some NullReferenceException caused in client’s code.

  6. sunly

    Said on September 23, 2009 :

    Excellent Post!

  7. Milan Vrhovac

    Said on October 13, 2009 :

    The value of Empty is a read-only instance of EventArgs equivalent to the result of calling the EventArgs constructor.

Post a Comment