Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking if a nullable bool is null or not [duplicate]

Tags:

c#

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.

like image 885
Amin Avatar asked Nov 09 '12 08:11

Amin


People also ask

How do I check if a Boolean is null or empty in C#?

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.

How do you check if a Boolean is nullable?

(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 { .... }

How do you check if something is nullable?

GetUnderlyingType() != null to identity if a type is nullable.

IS null Boolean false C#?

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.


1 Answers

if (!nullableBool.HasValue)
{
    // null
}

You also can directly compare it with null.

like image 152
tukaef Avatar answered Sep 29 '22 20:09

tukaef