¿No se puede convertir implícitamente el tipo bool?

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?)

Por ejemplo:

public virtual bool? MyBool

if (!MyBool){}

preguntado el 01 de febrero de 12 a las 01:02

In short, nullable bools are confusing. (just look at SQL) -

I don't think this is too confusing, it is just Ternary Logic: 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. -

3 Respuestas

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

En cambio, puedes escribir if (MyBool != true) or if (MyBool == false), depending on whether you want to include null. (and you should add a comment explaining that)

Respondido 01 Feb 12, 05:02

Another valid check is MyBool ?? false, although I generally prefer MyBool.GetValueOrDefault(). - Anthony Pegram

@AnthonyPegram: However, that requires extra parentheses for negation, and is also more confusing. - SLaks

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

You have to use MyBool.Value

por ejemplo:

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.

Respondido 01 Feb 12, 05:02

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

Respondido 01 Feb 12, 05:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.