As you read the title of this post you may ask yourself - Hmmm, raising an event... wasn't that achievable with 1-2 lines of code? How smaller could it get, 0 lines of code?
And you're almost right, to raise an event is not such a big deal. Supposing you have an event of type EventHandler.

public event EventHandler Clicked;  

Typically you have a virtual protected method which raises the event:

protected virtual void OnClicked(EventArgs e)  
    if (Clicked != null)  
        Clicked(this, e);  


Pretty simple unless you want to be thread safe (well... almost thread safe), then you should add one additional line:

protected virtual void OnClicked(EventArgs e)  
    var handler = Click;  
    if (handler != null)  
        handler(this, e);  


You could go on and live with it but as you add more and more events to your class you could start looking for ways to optimize the repetitive work.
One possible way to optimize it is to assign an empty delegate by default to your events:

public event EventHandler Clicked = delegate {};  

then in the virtual method you could just have:

protected virtual void OnClicked(EventArgs e)  
    Clicked(this, e);  


You'll be thread safe and you won't need to check for a null event. And you'll have less lines of code :)

If you don't like this approach (maybe because of the empty delegate) or if you have to deal with events which you can't modify, you could still make your life easier using an extension method.

static public void Raise(this EventHandler eventHanlder, object sender, EventArgs e)  
    if (eventHandler != null)  
        eventHandler(sender, e);  

Then when you want to raise the event you could just do:

Clicked.Raise(this, e);  


Should you be using .NET 2.0 you could still use a helper class and do the following:

EventHelper.Raise(Clicked, this, e);  


Hope this helps :)

About the Author

Hristo Kosev



Comments are disabled in preview mode.