24

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){}
MADCookie
  • 2,596
  • 3
  • 26
  • 46
user603007
  • 11,416
  • 39
  • 104
  • 168
  • 2
    In short, nullable bools are confusing. (just look at SQL) – SLaks Feb 01 '12 at 01:40
  • I don't think this is too confusing, it is just Ternary Logic: http://en.wikipedia.org/wiki/Three-valued_logic - I actually like it because I like the notion of something having no value. In other words, uninitialized vs. initialized. – dyslexicanaboko Jul 02 '12 at 04:06

3 Answers3

30

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)

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 6
    Another valid check is `MyBool ?? false`, although I generally prefer `MyBool.GetValueOrDefault()`. – Anthony Pegram Feb 01 '12 at 01:41
  • @AnthonyPegram: However, that requires extra parentheses for negation, and is also more confusing. – SLaks Feb 01 '12 at 01:51
  • I do not disagree on the first, but I don't find the second any more difficult to use or understand. Generally, I do not like direct comparisons to true or false, although I do exactly that in Linq-to-EF queries because the method is not supported. – Anthony Pegram Feb 01 '12 at 01:58
9

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.

NotMe
  • 87,343
  • 27
  • 171
  • 245
2

You need to check if it has a value. What do you want to do if MyBool == null?

if( MyBool.HasValue && !MyBool.Value ) // MyBool is false
if( MyBool.HasValue && MyBool.Value ) // MyBool is true
if( !MyBool.HasValue ) // MyBool is null
The Real Baumann
  • 1,941
  • 1
  • 14
  • 20