When there are no subscribers to an event how do I ensure that an exception will not be thrown if the event is fired.
// Delegate declaration
public delegate void _delDisplayChange(object sender,string option);
// Event declaration
public event _delDisplayChange DisplayChange;
//throwing the event
DisplayChange(this, "DISTRIBUTION");
Change this:
to this:
This will ensure your event will always have at least one subscriber.
Here is the recommended way to do it:
Copying the event handlers enumeration before checking does two things:
Also, you are not using the standard Event protocol. Your delegate should be:
Where OptionsEventArgs derives from EventArgs. Going a step further, in .Net 3.5, you should never define a delegate like this. Instead, you should just define your event:
I like to take it even one step further by defining this class:
Then, you don't need to define OptionsEventArgs:
Just some stuff to think about...
As Brian said: many sources suggest making a copy of the event before checking that it is not null:
This helps to make your code more thread-safe because the value of displayChangeCopy will not change between the null check and the invocation.