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?
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More
JOHN Said on Sep 22, 2008 :
To be honest, whenever I need empty args, I just pass a null.
Works for me.
Matti Lehtinen Said on Sep 23, 2008 :
Great tip! I have always used new EventArgs() without knowing there is a better alternative.
sirrocco Said on Sep 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
Rinat Abdullin Said on Sep 23, 2008 :
There is a bit more to the events
http://rabdullin.com/some-tips-on-writing-event-handling-code-in-c-net/
Andrei Rinea Said on Sep 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.
sunly Said on Sep 23, 2009 :
Excellent Post!