[ACCEPTED]-NullReferenceException when triggering event-event-handling

Accepted answer
Score: 34

You need a null check - in C# you can't 9 call events when there are no handlers registered 8 on that event.

The normal thing would be 7 to implement an OnConnectFailed method:

protected virtual void OnConnectFailed(e as EventArgs) {
    EventHandler tmp = connectFailed;
    if(tmp != null)
        tmp(this,e);
}

Also, the 6 first argument to the event handler should 5 be this, not the exception. If you need to pass 4 the exception to the event handler, create 3 an EventArgs class with an exception property.

Also, there's 2 no point in raising an event from the constructor... nothing 1 has a chance to add a handler to it.

Score: 11

Also in C# 6 you may do the null checking this way:

connectFailed?.Invoke(this, e); 

0

Score: 9

Found it,

public delegate void OnRequestReceivedHandler(object sender);
public event OnRequestReceivedHandler ReqeustReceived = delegate { };

0

Score: 1

'connectFailed' is an event. If nobody susbcribes 13 to the event, it will be null, so you have 12 to check for the null case.

To make this 11 safe you would need a null check, i.e:

if (connectFailed != null)
    connectFailed(e, new EventArgs()); 

However, this 10 pattern is not enough, because of multithreading. The 9 recommended approach is this:

EventHandler temp = connectFailed;
if (temp != null)
    temp(e, new EventArgs()); 

This not only 8 checks for the null condition, but also 7 copies the event first to ensure it is thread-safe 6 (if the event queue is changed by one thread 5 while the event is being handled on another 4 thread, the behaviour could be undefined. By 3 copying it first you ensure that the subscriber 2 list remains the same for the duration of 1 the event-handling process)

More Related questions