0

I want to use a nullable boolean in an if statement. But I get the following compiler error: Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) csharp(CS0266)

How can I easily cast bool? to bool?

This is sample code that throws the error:

bool? nullable = null;
if(nullable) return;
Cornelius Roemer
  • 3,772
  • 1
  • 24
  • 55
  • I created this duplicate question on purpose, because it wasn't straightforward to find the duplicates quickly through Google. Also, the answers to the duplicates weren't straightforward either. – Cornelius Roemer Jan 13 '21 at 13:23

1 Answers1

1

For C# 8.0 upwards, the quickest way is to use the binary null-coalescing operator ?? which returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result as follows:

bool? nullable = null;
if(nullable ?? false) return; //if nullable is null, default to false

Depending on what you want to happen if nullable is null you put false or true on the right hand side of ??.

See documentation for ?? on MSDN: https://learn.microsoft.com/en-gb/dotnet/csharp/language-reference/operators/null-coalescing-operator

Another option is to use nullable.GetValueOrDefault() which does not allow one to return true in case of null however (thanks user:Magnus)

To work around this caveat, you can first handle the case if nullable is false, then use .GetValueOrDefeault() knowing that the default will never be used:

if(nullable == null ? false : nullable.GetValueOrDefault()) return;
Cornelius Roemer
  • 3,772
  • 1
  • 24
  • 55