-1

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?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • 2
    I think you would get away with `if (maybeAThing?.IsAGoodThing == true) { ... }` – Astrid E. Nov 24 '22 at 15:02
  • 1
    [How to use bool? in if statement?](https://stackoverflow.com/questions/65702823/how-to-use-bool-in-if-statement) or many similar questions on topic: "CS0266 bool" – Selvin Nov 24 '22 at 15:11

3 Answers3

2

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 }
canton7
  • 37,633
  • 3
  • 64
  • 77
2

You can just write:

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


null == true  //Nope
false == true //Nope
true == true  //Yes
Magnus
  • 45,362
  • 8
  • 80
  • 118
2

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939