Search code examples
c#.net-6.0nullable

How can I use the null-conditional operator to safely and briefly check a nullable reference type's property


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?


Solution

  • 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 }