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?