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){}
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)
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With