WDUK
WDUK

Reputation: 1524

Null check on a property error

I have a simple null check on a property getting but for some reason it won't compile.

This is how it looks

    private TestObj _someObj;
    public bool IsActive
    {
        get { return _someObj?.IsActive; }
    }

I thought the ? would return false if _someObj was null ? Have i misunderstood its use here?

The error i get:

Cannot implicitly convert type `bool?' to `bool'

I tried adding an if statement around it but same problem occurred.

Hope you can help explain my misunderstanding.

Upvotes: 1

Views: 61

Answers (2)

AustinWBryan
AustinWBryan

Reputation: 3327

If _someObj is null, it has to return null, but if it's true or false it has to return that, therefore it returns a bool? which can be true, false, or null.

There are two ways to fix this. You can do:

public bool IsActive => _someObject ?? false;

The above is exactly the same as doing:

public bool IsActive => _someObejct != null ? _someObject : false;

It's going to return false if _someObject is null. Another solution is to change the type of IsActive to be a bool?, like this:

public bool? IsActive => _someObject;

And you don't have to use any null checking, only in that one instance. You will have to check if it is null everytime you want to use IsActive, which is properly not ideal.

Upvotes: 0

Nkosi
Nkosi

Reputation: 247521

_someObj?.IsActive is a nullable condition, so assuming IsActive is of type bool, using ?. will turn the result to a nullable bool bool?/Nullable<bool> which will conflict with the expected bool result of the property.

If _someObj is null then the result will also be null, so you will need to add a null-coalescing operator for that possibility

public bool IsActive {
    get { return _someObj?.IsActive ?? false; }
}

Upvotes: 1

Related Questions