(a ?: b) is equivalent to (if (a != null) a else b). So checking a nullable Boolean to true can be shortly done with the elvis operator like that: if ( a ?: false ) { ... } else { .... }
It be that you need to test if SessionManager is null before you access it, or maybe the HoldStringId needs to be tested for null, as well as that. Nullable types can be checked using the HasValue property, and their value can be retrieved with the Value property.
GetUnderlyingType() != null to identity if a type is nullable.
The compiler replaces null comparisons with a call to HasValue , so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues.
I think a lot of people concentrate on the fact that this value is nullable, and don't think about what they actually want :)
bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else { ... } // false or null
Or if you want more options...
bool? nullableBool = true;
if (nullableBool == true) { ... } // true
else if (nullableBool == false) { ... } // false
else { ... } // null
(nullableBool == true)
will never return true if the bool? is null :P
How about using GetValueOrDefault, which is pretty self-explaining and allows to use whatever default you want:
if (nullableBool.GetValueOrDefault(false)) {
}
You may not like it, but personally I find
if (x.HasValue && x.Value)
the most readable. It makes it clear you are working with a nullable type and it makes it clear you are first checking whether the nullable type has a value before acting on it conditionally.
If you take your version and replace the variable with x also it reads:
if (x ?? false)
Is that as clear? Is it obvious x is a nullable type? I'll let you decide.
If you want to treat a null
as false, then I would say that the most succinct way to do that is to use the null coalesce operator (??
), as you describe:
if (nullableBool ?? false) { ... }
Just think of bool? as having 3 values, then things get easier:
if (someNullableBool == true) // only if true
if (someNullableBool == false) // only if false
if (someNullableBool == null) // only if null
Another way is to use constant pattern matching:
if (nullableBool is true) {}
if (nullableBool is false) {}
if (nullableBool is null) {}
Unlike the operator ==
, when reading the code, this will distinguish the nullable type check from ordinary "code with a smell".
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