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 :
public class Foo
{
public event EventHandler FooEvent;
public Foo()
{
}
public void Execute()
{
if (FooEvent != null)
FooEvent(this, new EventArgs());
}
}
The problem with this is you have to test if the event is not null. and you might forget about it easily.
- 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()
{
OnFooEvent();
}
}
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()
{
FooEvent(this, new EventArgs());
}
}
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 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()
{
FooEvent.Raise(this, new EventArgs());
}
}
The advantages of this way is the readability, also the null check is centralized.