0

I am follow a tutorial and getting an error. Can rewrite statement:

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

Code:

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Ranu
  • 3
  • 1

1 Answers1

2

If you are in working in a previous version to C# 6, you can do this

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    if(PropertyChanged != null)
       PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Further reading

?. and ?[] null-conditional Operators (C# and Visual Basic)

Tests the value of the left-hand operand for null before performing a member access (?.) or index (?[]) operation; returns null if the left-hand operand evaluates to null.

and

The null-conditional operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stop

Update from Jeff's comment

The implementation you give above is one of the foremost use cases for ?. for thread safety - you should be saving the event field to a local variable before checking if it’s null and invoking – Jeff 1

and he is 100 percent correct

Ideally you should do this

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var changedEvent = PropertyChanged;
    if(changedEvent != null)
       changedEvent.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

For more information on this here is a reference to a relevant question provided by pinkfloydx33

Is C# 6 ?. (Elvis op) thread safe? If so, how?

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • The implementation you give above is one of the foremost use cases for ?. for thread safety - you should be saving the event field to a local variable before checking if it’s null and invoking – Jeff Jul 28 '18 at 08:22
  • Null conditional already uses a temporary variable when invoking event handlers. Though, see the second highest answer and also Eric's comments about it all here: https://stackoverflow.com/a/35786442/491907 – pinkfloydx33 Jul 28 '18 at 09:21
  • @pinkfloydx33 agreed and very correct, and its worth linking that answer as well for clarity into the update. thanks – TheGeneral Jul 28 '18 at 09:23