Self-Testing delegates: avoid checking for null before invocation?

static void CallIfNotNull(this Action action)
{
 if (action != null) action();
}

As an extension method, this is quite convenient to use.


public event EventHandler NoDataEventHandler = delegate{};

Declaring an event in this way means it will never be null. It will always, at a minimum, have a single no-op event handler hooked up.

In your case, probably

public event ResetTradesDelegate ResetTradesEvents = delegate{};

Firing an event is always going to have a race condition associated with it. You're either going to risk trying to call a delegate when it's null, or calling a delegate after the event has been unhooked. Eric Lippert wrote a pretty comprehensive post on this topic here. The technique above still suffers from the second type of race condition, so the event handlers need to be robust to being called after the event has been unhooked.

Tags:

C#

.Net