Here is the recommended way to do it:
protected void RaiseDisplayChanged(string message)
{
var handlers = DisplayChange;
if(handlers != null)
handlers(this, message);
}
Copying the event handlers enumeration before checking does two things:
- If DisplayChange handlers becomes null between the check and the firing, you don't die
- If the listeners modify the DisplayChange list while enumerating through it, you don't run into oddities.
Also, you are not using the standard Event protocol. Your delegate should be:
public delegate void DisplayChangeDelegate(object sender, OptionsEventArgs args);
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:
public event EventHandler<OptionsEventArgs> DisplayChanged;
I like to take it even one step further by defining this class:
public class EventArgs<T> : EventArgs
{
public T Payload { get; private set }
public EventArgs(T payload)
{
Payload = payload;
}
}
Then, you don't need to define OptionsEventArgs:
public event EventHandler<EventArgs<string>> DisplayChanged;
Just some stuff to think about...