Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type bool?

Tags:

I am trying to convert my nullable bool value and I am getting this error.

Cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?) 

For example:

public virtual bool? MyBool   {     get;     set;   }  if (!MyBool){} 
like image 251
user603007 Avatar asked Feb 01 '12 01:02

user603007


2 Answers

As the error states, you can't use a bool? in a conditional. (What would happen if it's null?)

Instead, you can write if (MyBool != true) or if (MyBool == false), depending on whether you want to include null. (and you should add a comment explaining that)

like image 107
SLaks Avatar answered Oct 22 '22 06:10

SLaks


You have to use MyBool.Value

for example:

if (!MyBool.Value) { } 

However, you should test that it does indeed have a value to begin with. This tests that MyBool has a value and it is false.

if (MyBool.HasValue && !MyBool.Value) { } 

Or you might really want the following that runs the code block if it either has not been assigned or has is false.

if (!MyBool.HasValue || !MyBool.Value) { } 

The question really boils down to whether you truly intended to have a nullable boolean variable and, if so, how you want to handle the 3 possible conditions of null, true or false.

like image 27
NotMe Avatar answered Oct 22 '22 06:10

NotMe