Dirk Dastardly
Dirk Dastardly

Reputation: 1047

Firing events in C#

I've noticed in all the samples I've seen for events in C# that firing the event is written as:

PropertyChangedEventHandler handler = PropertyChanged;
if(handler != null)
    handler(this, new PropertyChangedEventArgs(propertyName));

What is the different between that and just writing:

if(PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

Upvotes: 2

Views: 234

Answers (2)

GvS
GvS

Reputation: 52518

In your second example, you call the getter of PropertyChanged twice. In a multithreaded environment it is possible, that the value is changed in between the calls.

This is prevented in your first example, by first making a local copy.

Upvotes: 8

plinth
plinth

Reputation: 49189

In the second case, the value of PropertyChanged might be mutated between the if and the invoke if you're running multithreaded. It is not recommended.

You might also try initializing your event handler to have an empty handler like this:

public EventHandler<PropertyChangeEventArgs> PropertyChanged = (s, e) => { };

which means it will never be null, so you can just fire it is as.

Upvotes: 4

Related Questions