0

When doing a null check on an event object, Visual Studio is changing the code color to light grey. If I'm not mistaken , it normally implies that this line is unnecessary. Obviously, it is not the case in my situation (or is it ?). See my example below:

 public event PropertyChangedEventHandler PropertyChanged;

    string test; 

    protected void OnPropertyChanged (string propertyName)
    {
        if (PropertyChanged != null) {    //This line is grey
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }  //This line is grey
        if (test != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

Here is the screen shot: enter image description here

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
scharette
  • 9,437
  • 8
  • 33
  • 67

2 Answers2

5

If you right click and view (Quick Actions and Refactorings) the suggested fix you will see that the null reference check can be performed on the same line as the raising of the event through the use of the ? operator (Safe Navigation Operator).

The action it will suggest is the following:

this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
Bijington
  • 3,661
  • 5
  • 35
  • 52
1

It's a code suggestion. If you hover your cursor over it, you will see a little "Quick Actions" icon in the margin, and if you click it you will see that it's suggesting you could improve your statement -- make it more succinct -- by using a null conditional operator:

enter image description here

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
rory.ap
  • 34,009
  • 10
  • 83
  • 174
  • +1 for ss. After restarting my VS that's exactly how I could see it. It even suggest potential fixes. Thanks for your insight – scharette Jun 05 '18 at 13:05