-3

I have come across codes like

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

I was trying to find what is the meaning of PropertyChanged? in the line of code above.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Athena_92
  • 29
  • 5

1 Answers1

0

This is the syntax for null propagation which was introduced in c# 6.0. Here the ? is the null-conditional operator. This code is equivalent to:

if(!(PropertyChanged is null))
    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propName));
Soleil
  • 6,404
  • 5
  • 41
  • 61
  • 2
    It's more `var handler = PropertyChanged; if (handler != null) { handler.Invoke... }`. This is thread safe, your code is not. – Simon Mourier Nov 06 '21 at 16:43
  • @SimonMourier Your code is not more thread safe than mine. – Soleil Nov 06 '21 at 16:51
  • 1
    @Soleil Wrong, in your code PropertyChanged may become null between the null check and the Invoke call. – Clemens Nov 06 '21 at 16:55
  • 1
    @Soleil In a multi threaded application, an event handler can be cleared between the null check and the invoke, triggering an exception. Taking a copy prevents this. – Peregrine Nov 06 '21 at 17:07