In this case my variable Truth is a nullable variable. My question is simple
Would there be anything wrong writing it like this?
if ((bool)Truth) {}
or should i stick with this?
if (Truth == True) {}
Never worked with nullable variables not certain if there is even a difference other then possibly if ((bool)Truth) {} taking one additional step?
These are semantically different. If Truth
is null
, the cast will fail with an InvalidOperationException: Nullable object must have a value
. The second one will not fail and just execute if the value has true
in it. Unless null
should be an invalid value at this point in your program, go with the second version.
As stated be Jesse Slicer, nullable values could be casted to their non-nullable equivalent type only if you're sure they are not null. Even in this case, I would not do it since it may not be the most readable way to do it.
The best way to use a nullable boolean is :
if (myBool.HasValue && myBool.Value)
This ensures that myBool is not null (HasValue) and is true (Value returns the boolean value). Note that this example assumes that you do not want to enter the if statement if your nullable bool is null.
By the way, all nullable types provides a HasValue and a Value property. I'd rather use the Value property than a cast since it clearly states that you're manipulating a nullable type.
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