How do you convert a nullable bool? to bool in C#?
I have tried x.Value or x.HasValue ...
You can use the null-coalescing operator: x ?? something, where something is a boolean value that you want to use if x is null.
Example:
bool? myBool = null;
bool newBool = myBool ?? false;
newBool will be false.
If you're going to use the bool? in an if statement, I find the easiest thing to do is to compare against either true or false.
bool? b = ...;
if (b == true) { Debug.WriteLine("true"; }
if (b == false) { Debug.WriteLine("false"; }
if (b != true) { Debug.WriteLine("false or null"; }
if (b != false) { Debug.WriteLine("true or null"; }
Of course, you can also compare against null as well.
bool? b = ...;
if (b == null) { Debug.WriteLine("null"; }
if (b != null) { Debug.WriteLine("true or false"; }
if (b.HasValue) { Debug.WriteLine("true or false"; }
//HasValue and != null will ALWAYS return the same value, so use whatever you like.
If you're going to convert it to a bool to pass on to other parts of the application, then the Null Coalesce operator is what you want.
bool? b = ...;
bool b2 = b ?? true; // null becomes true
b2 = b ?? false; // null becomes false
If you've already checked for null, and you just want the value, then access the Value property.
bool? b = ...;
if(b == null)
throw new ArgumentNullException();
else
SomeFunc(b.Value);
This answer is for the use case when you simply want to test the bool? in a condition. It can also be used to get a normal bool. It is an alternative I personnaly find easier to read than the coalescing operator ??.
If you want to test a condition, you can use this
bool? nullableBool = someFunction();
if(nullableBool == true)
{
//Do stuff
}
The above if will be true only if the bool? is true.
You can also use this to assign a regular bool from a bool?
bool? nullableBool = someFunction();
bool regularBool = nullableBool == true;
witch is the same as
bool? nullableBool = someFunction();
bool regularBool = nullableBool ?? false;
This is an interesting variation on the theme. At first and second glances you would assume the true branch is taken. Not so!
bool? flag = null;
if (!flag ?? true)
{
// false branch
}
else
{
// true branch
}
The way to get what you want is to do this:
if (!(flag ?? true))
{
// false branch
}
else
{
// true branch
}