Home > Software design >  How can I use the null-conditional operator to safely and briefly check a nullable reference type�
How can I use the null-conditional operator to safely and briefly check a nullable reference type�

Time:11-25

Given code like:

Thing? maybeAThing = GetThing();

I want to write logic that safely checks if the object is not null and has a certain property:

if(maybeAThing is not null && maybeAThing.IsAGoodThing){ ... }

But this syntax seems a bit messy. I thought the null-conditional operators were supposed to let me do this as any test will fail as soon as null is encountered:

if(maybeAThing?.IsAGoodThing){...}

But this gives compiler error:

CS0266 cannot implicitly convert bool ? to bool

It seems the 'nullableness' is extending to the return value (bool?) instead of the test failing as soon as maybeAThing is determined to be null.

Is this specific to NRTs rather than nullable value types? Is there a way to do this without having to write additional clauses, and if not then what is my misunderstanding in the way the language works?

CodePudding user response:

You can write some variant of:

maybeAThing?.IsAGoodThing == true
maybeAThing?.IsAGoodThing ?? false
(maybeAThing?.IsAGoodThing).GetValueOfDefault(false)

You can also use a property pattern:

maybeAThing is { IsAGoodThing: true }

CodePudding user response:

You can just write:

if(maybeAThing?.IsAGoodThing == true){...}


null == true  //Nope
false == true //Nope
true == true  //Yes

CodePudding user response:

You can use

if(maybeAThing?.IsAGoodThing == true){...}

This converts the Nullable<bool> to a bool.

Lifted Operators

For the equality operator ==, if both operands are null, the result is true, if only one of the operands is null, the result is false; otherwise, the contained values of operands are compared.

  • Related