2

I get this error NullReferenceException was unhandled by user code. The error occurs on this line

PropertyChanged(this, new PropertyChangedEventArgs("AboveAircraft"));

I tried if( this != null) and it still got the error. How do I get rid of it?

The code looks like this:

public int AboveAircraft
{
        get { return _above; }
        set
        {
            if (SetProperty(ref _above, value, "AboveAircraft") && _updateModel)
            {
                if (Model.AltitudeBand == null)
                {
                    Model.AltitudeBand = new AltitudeBand();
                }

                if (this != null && AboveAircraft != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("AboveAircraft"));
                    if (_above < _below)
                    {
                        BelowAircraft = _above;
                    }
                }

                Model.AltitudeBand .Above = new AltitudeBandLimit() { Unit = AltitudeUnit.Foot, Value = _above };
            }
        }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jane wang
  • 298
  • 1
  • 3
  • 16
  • It may be that you're getting the exception not from this code but from code that is bound to these property change events. Do you have any data bindings that refer to your `AboveAircraft` property? – Jacob Aug 31 '13 at 19:27
  • 2
    `this` cannot, by definition, ever be `null` - `this` refers to the current instance of your class... it being `null` would mean there's no instance, so the condition would always evaluate to `true`. See http://stackoverflow.com/questions/5055068/within-a-c-sharp-instance-method-can-this-ever-be-null – Mathieu Guindon Aug 31 '13 at 19:28
  • Yes, AboveAircraft is bound to a textbox in the xaml file. – Jane wang Aug 31 '13 at 19:29
  • 1
    Step through the code in VS line by line and check your objects to see which one is null - it could be *value*. – keenthinker Aug 31 '13 at 19:30
  • @VaibhavDesai IMO we need to know what we're doing(what we write), else better don't do. – Sriram Sakthivel Aug 31 '13 at 19:38

1 Answers1

6

You need to check if PropertyChanged is null:

if (PropertyChanged != null)
{
    PropertyChanged(this, new PropertyChangedEventArgs("AboveAircraft"));
}

It will only be not null if there is at least one handler registered elsewhere.

ChrisF
  • 134,786
  • 31
  • 255
  • 325