Let’s say you’re feeling particularly lazy today. There’s a situation where you need a state that require 3 states. Maybe it’s something that’s loaded later, whenever another script needs access to this resource. Maybe you need to add a new mode, despite already using a boolean to differentiate which mode you’re in. Either way, memory isn’t your first concern right now: you want something fast.

The “correct” method is to use an enumerator:

Enumerators

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

publicenumTriState:byte// Byte for reduced memory use.

{

FirstState,

SecondState,

ThirdState

}

TriState state=TriState.FirstState;

if(state==TriState.FirstState)

{

Console.WriteLine("state 1");

}

// Will print:

// state 1

But no, today you’re lazy. Or perhaps you really have very little time and need something ready now. Enter the question mark.

Nullable Boolean

C#

1

2

3

4

5

6

7

8

bool?state=null;

if(state==null)

{

Console.WriteLine("state 1");

}

// Will print:

// state 1

That’s right, state can now have 3 values: null, true, and false.

What is this madness? You’ve just created a Nullable Type, a struct that can contain a value or null. It’s useful for other types of variables that cannot be set to null, such as int, double, and any instances of structs and enums. To retrieve the value of a Nullable Type, or compare it to an actual value, simply use the Value property.

Nullable Ints

C#

1

2

3

4

5

6

7

8

int?state=2;

if(state.Value==2)

{

Console.WriteLine("state 2");

}

// Will print:

// state 2

You can check whether a Nullable Type is null or not by simply comparing it to null, or using the HasValue property.

Null Check

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

double?isNull=null;

if(isNull==null)

{

Console.WriteLine("Is Null");

}

if(isNull.HasValue==false)

{

Console.WriteLine("Is Null");

}

// Will print:

// Is Null

// Is Null

Other than that, for any Nullable primitives, you can use their regular operator like an actual variable.