Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I have to explicitly ask whether a nullable boolean var is true?

Tags:

c#

c#-3.0

c#-4.0

bool? nullableVar;
if(nullableVar) 

gives me an error but

if(nullableVar==true) 

evaluates fine.

Not sure I follow on why that is given that if the bool wasn't nullable would evaluate fine?

like image 981
Sali Avatar asked Jan 26 '26 20:01

Sali


1 Answers

The condition expression of an if has to be implicitly convertible to bool. Nullable<bool> is not convertible to bool, but the second expression is already of type bool, so it's okay. Looking at the IL, I believe the second expression is really being compiled to:

if (nullableVar.GetValueOrDefault())
like image 160
Jon Skeet Avatar answered Jan 29 '26 10:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!