Raising an event in C#






2.05/5 (5 votes)
Raising an event in C#, methods and Critics
Introduction
During this years, I come across many habits of developers regarding raising an Event, In the present Post I will try to summarize all those ways and give some critics.
Code
- The first and intuitive way is to declare and use the event directly like in the example below :
- The second approach is to create a function that raise the event for you:
public class Foo { public event EventHandler FooEvent; public Foo() { } protected void OnFooEvent() { if (FooEvent == null) return; FooEvent(this, new EventArgs()); } public void Execute() { //Do the work OnFooEvent(); //Continue the work } }
Although this simplify the way we call the event but we are always able to call the event directly and so we may have a
NullReferenceException
. also we should define a function that raises the event in every class. - The third way is a good way to be sure that we won't have a
NullReferenceException
.public class Foo { public event EventHandler FooEvent = new EventHandler((e, a) => { }); public Foo() { } public void Execute() { //Do the work FooEvent(this, new EventArgs()); //Continue the work } }
With this way, we will never have a risk of
NullReferenceException
. - The forth way is to create an extension function that raises the event and use it.
public class Foo
{
public event EventHandler FooEvent;
public Foo()
{
}
public void Execute()
{
//Do the work
if (FooEvent != null)
FooEvent(this, new EventArgs());
//Continue the work
}
}
The problem with this is you have to test if the event is not null. and you might forget about it easily.
public static class EventHelper
{
public static void Raise(this EventHandler eventHandler, object sender,EventArgs args)
{
if (eventHandler == null)
return;
eventHandler(sender, args);
}
}
public class Foo
{
public event EventHandler FooEvent;
public Foo()
{
}
public void Execute()
{
//Do the work
FooEvent.Raise(this, new EventArgs());
//Continue the work
}
}
The advantages of this way is the readability, also the null check is centralized.