While reviewing some code at work the last days, I noticed I had a lot of similar methods I used to raise events. Basically, I did a test to check if the EventHandler is not null, and in this case, I raise the event:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
// declaration of the event
public event EventHandler Saved;
 
// method I use to raise the event
private void OnSaved()
{
  if (this.Saved != null)
    this.Saved(this, EventArgs.Empty);
}

In some of my classes, I had around 10 methods like this one to do the check, and raise the event if the associated event handler is not null. I was thinking about creating an extension method that would do this job for me… And actually, it’s very simple ! Here is the code:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
 /// <summary>
/// Raise an event with a given EventArgs
/// </summary>
/// <param name="handler">EventHandler to raised</param>
/// <param name="sender">Sender of the event</param>
/// <param name="e">Argument of the event</param>
public static void Raise(this EventHandler handler, object sender, EventArgs e)
{
    if (handler != null)
    {
        handler(sender, e);
    }
}

Now, I can remove all methods that looks like the first I mentioned in the post, and simply write

?View Code CSHARP
1
Saved.Raise(this, EventArgs.Empty);

I also created an overload of the extension method that does not supply an EventArgs (in case you want to use EventArgs.Empty) and also a generic version (in case you want to use an EventHandler).
You can download the associated class here.