Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nullable bool as tri-state variable in C#

Tags:

c#

boolean

state

Is there any merit to using a nullable bool to store a tri-state value? For example, null == 1st state, false == 2nd state, true == 3rd state?

The overhead is probably higher than using a byte enum, but I'm curious.

like image 616
Petrus Theron Avatar asked Mar 16 '11 10:03

Petrus Theron


People also ask

What is nullable bool in C#?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

Can bool null?

Amongst other, more important distinctions, value types, such as bool or int, cannot contain null values.

How check Boolean value is null or not 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.


1 Answers

You should get a copy of Framework Design Guidelines.

There on page 177 is a chapter Choosing Between Enum and Boolean Parameters.

One of the points there is:

  • DO NOT use Booleans unless you are absolutely sure there will never be a need for more than two values.
like image 125
Oliver Avatar answered Sep 20 '22 17:09

Oliver