Possible Duplicate:
Which is preferred: Nullable<>.HasValue or Nullable<> == null?
I know questions like this have been asked many times. But I never found an answer to how to check if a nullable bool is null or not. Here is an answer I have to this:
bool? nullableBool;
if (nullableBool == true){
}else if (nullableBool == false){
}else{
}
But I was wondering if there is a better and more straight to the point way in order to minimize useless codes? Thanks.
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.
(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 { .... }
GetUnderlyingType() != null to identity if a type is nullable.
False is a value, null is lack of a value. C# gets it right I think. Other languages that were built without a boolean type or a concept of a pointer (or nullable type) just overloaded an int to mean all these different things.
if (!nullableBool.HasValue)
{
// null
}
You also can directly compare it with null
.
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