0

Say I have a class that can fire some event like so

public SomeTypeOfEvent SomeEvent;
public delegate void SomeTypeOfEvent();
public void FooBar()
{
    if (SomeEvent != null)
        SomeEvent();
}

Is this the correct way to check to see if the SomeEvent delegate has any subscribers? I faintly remember being told a few times that this is not correct because between the checking of the delegate and its firing the subscriber(s) to the event could be removed.

What is the proper/accepted way to check to see if a delegate is null?

KDecker
  • 6,928
  • 8
  • 40
  • 81

2 Answers2

6

It's perfectly fine way, if you are not bothering with more than one thread. If you are, then this is not thread safe, because in the middle of the != check another thread may null the delegate value and you will get NullReferenceException.

In C# 6.0 the proper way is SomeEvent?.Invoke() using new null-conditional operator.

MSDN recommends it:

Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code.

PropertyChanged?.Invoke(e)

In prior C# versions you can store the delegate value into the temporary variable, and it is the proper way to go.

var handler = this.PropertyChanged;
if (handler != null)
    handler(…)
Dmytro Marchuk
  • 478
  • 5
  • 10
  • Hmm looks like I need to get C#6, I really like that syntax a lot more than the later. Either way, thank you! This cleared it up for me! – KDecker Mar 14 '16 at 16:58
0

I usually do it this way (haven't used C# 6.0 much yet).

public event EventHandler SomeEvent;

private void OnSomeEvent() {
    var someEvent = SomeEvent;
    if (someEvent != null) {
        someEvent(this, EventArgs.Empty);
    }
}
Maarten
  • 22,527
  • 3
  • 47
  • 68