Possible Duplicate:
Is there a downside to adding an anonymous empty delegate on event declaration?
Is it a good practice to define an empty delegate body for a event so that you do not need to worry raise a event which have no event handler? ( no need to check whether event is null).
Like code below:
public event EventHandler<LoadEventArgs> LoadedData = delegate { };
I've certainly found it useful, yes. There will be a tiny, tiny performance cost - but the benefit in readability for not having to perform the nullity test makes it worth it IMO.
It's worth pointing out that this is one of the few times when it's good to use an anonymous method rather than a lambda expression - otherwise you have to name the parameters that you're going to ignore, like this:
public event EventHandler<LoadEventArgs> LoadedData = (sender, args) => {};
I don't like having to name things I'm not intending to use :)
I would not do this.
There are two reasons for this. Firstly, it's standard to simply check the handler for null
before calling this. You see this all over the place, in examples, in the Microsoft reference source and in the manuals.
Second, initializing your events this way allocates unnecessary objects when creating your class. This will put extra memory pressure on your application without a real need. This is because:
public event EventHandler<LoadEventArgs> LoadedData = delegate { };
translates to:
public event EventHandler<LoadEventArgs> LoadedData = new EventHandler<LoadEventArgs>delegate { });
If you don't do this already, wrapping your events in specific methods helps a lot:
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
if (MyEvent != null)
MyEvent(this, e);
}
You can make this thread safe(r) using the following:
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
var handler = MyEvent;
if (handler != null)
handler(this, e);
}
I don't normally use C# but it seems like good practice to me. This is a textbook application of the 'Null Object' pattern. As noted, this will cost in terms of performance when the empty delegate actually runs, but gains in terms of performance every other time, when you don't have to check for an explicit null - so it should also be a net win performance-wise whenever the frequency of empty delegates is low.