Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting an exception with the following code?

Tags:

c#

viewmodel

I have a property defined in an interface as:

 Boolean IsBusy { get; }

It is implemented in the class as:

private Boolean _isBusy = false;
public Boolean IsBusy
    {
        get
        {
            return this._isBusy;
        }

        private set
        {
            if (this._isBusy != value)
            {
                this._isBusy = value;
                this.OnPropertyChanged("IsBusy");
            }
        }
    }

Then when I run the app, I always get following kind of error when check IsBusy value in constructor:

'IsBusy' threw an exception of type 'System.NullReferenceException' bool {System.NullReferenceException}

I can't figure it out. If I change all Boolean to bool, get same error.

How can I fix it?

like image 605
KentZhou Avatar asked Jan 25 '26 00:01

KentZhou


2 Answers

You fix it by checking whether OnPropertyChanged is null before calling it, assuming OnPropertyChanged is an event or a delegate variable (you haven't made this clear). This has nothing to do with bool or Boolean, which are equivalent (assuming that Boolean is resolved to System.Boolean).

I can't see any other reason it would throw NullReferenceException - although it would really help you could clarify whether you were calling the getter or the setter at the time it threw the exception. A short but complete example would be even more helpful.

like image 198
Jon Skeet Avatar answered Jan 26 '26 16:01

Jon Skeet


bool is just a syntax shortcut for Boolean

like image 42
Liviu Mandras Avatar answered Jan 26 '26 18:01

Liviu Mandras