Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange NullReferenceException with INotifyPropertyChanged implementation [duplicate]

I'm implementing INotifyPropertyChanged in a base class as follows:

public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void RaisePropertyChanged(string propertyName)
    {
        var propChangedHandler = PropertyChanged;

        if (propChangedHandler != null)
        {
            var args = new PropertyChangedEventArgs(propertyName);
            propChangedHandler(this, args);
        }
    }
}

I'm using it as follows:

RaisePropertyChanged("Name");

I'm getting a NullReferenceException while the arguments, "this" and the handler are NOT null. Can anyone shed some light on this?

Thanks.

-> Full stacktrace of the exception: http://pastebin.com/bH9FeurJ

UPDATE The exception occurs when I overwrite an instance of the class which contains this property. Simplified example:

public class Person : INotifyPropertyChanged
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged("Name");
        }
    }

// More properties etc.
}

-snip-

public class ViewModel
{
    private Person _dummyPerson;
    public Person DummyPerson
    {
        get { return _dummyPerson; }
        set
        {
            _dummyPerson = value;
            RaisePropertyChanged("DummyPerson");
        }
    }

    public void Foo()
    {
        DummyPerson = new DummyPerson(); 
        // this line throws the NRE, strangly enough the very FIRST time it works fine
    }
}

-snip-

I'm using this DummyPerson and its Name property to databind to the UI. The second and all following attempts thereafter result in the NullReferenceException.

like image 455
rumblefx0 Avatar asked Dec 12 '11 14:12

rumblefx0


1 Answers

The exception isn't raised in your sample code, it is raised in one of the subscribed event handlers. Go through it step by step in debugger or turn on the switch "Thrown" for "Common Language Runtime Exceptions" in "Debug" - "Exceptions" menu of Visual Studio. Then you will be able to find out the reason.

like image 51
Fischermaen Avatar answered Oct 28 '22 04:10

Fischermaen