Ranu
Ranu

Reputation: 13

?. Invalid Expression Term

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));
}

Upvotes: 1

Views: 680

Answers (1)

TheGeneral
TheGeneral

Reputation: 81483

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?

Upvotes: 2

Related Questions