Tim Van Wassenhove

Passionate geek, interested in Technology. Proud father of two

09 Jan 2010

About raising events

Very often i see people write the following to ‘safely’ raise a method

public event EventHandler Stopped;

void RaiseStoppedEvent()
{
	if (Stopped != null) Stopped(this, EventArgs.Empty);
}

Some developers think that they should program defensively and avoid the potential concurrency problem

public event EventHandler Stopped;

void RaiseStoppedEvent()
{
	var handler = Stopped;
	if (handler!= null) handler(this, EventArgs.Empty);
}

And then there is Tim’s way to raise an event: (If i’m not mistaken it was Ayende who once blogged about this)

public event EventHandler Stopped = delegate { };

void RaiseStoppedEvent()
{
	Stopped(this, EventArgs.Empty);
}