Lazy Trick with C#: Tri-state Boolean (or how to abuse Nullable Types)

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:

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

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.

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

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

Happy coding!

No Comments

Have something to say? Leave a comment!

We use cookies to ensure that we give you the best experience on our website.