Lets take a simple example of declaring and raising a custom event. Look at the code below:
public class EventTestClass { public event EventHandler NewEvent; protected void OnNewEvent() { NewEvent(this, EventArgs.Empty); // Above code will raise System.NullReferenceException // exception if there is no handler registered with it. } }
As you know if if don't attach any handler to the NewEvent above then the OnNewEvent will throw exception because the NewEvent is null at that time. To get rid of this we generally put a null check on the event as shown below:
public class EventTestClass { public event EventHandler NewEvent; protected void OnNewEvent() { if (NewEvent != null) { NewEvent(this, EventArgs.Empty); } } }
There could be better way solving problem look at the solution below:
public class EventTestClass { public event EventHandler NewEvent = delegate { }; protected void OnNewEvent() { NewEvent(this, EventArgs.Empty); } }
The above code will work perfectly fine even if you don't attach any handler to the event. This is because the event is not null now as we have already registered on empty handler with it.
11 comment(S)