Borbin the 🐱

.NET nullable type

27 January, 2013


A .NET nullable type is a data type accepting a null value.

So how is it different from assigning a null value in C or C++?

In C/C++ a null is a 0.

This is how the null is defined in C/C++:

#define NULL 0

The define statement is a text processor directive to use the new defined value in the pre-parsing stage on the source code before the compiler sees it. BTW: Values like true or false are also int:

#define FALSE 0

#define TRUE 1

But in .NET a null and a 0 are two different values. In C#, basic data types like int or bool are not nullable types by default.

Promoted to a nullable type adds the null. Take for example a bool: The bool type is an enumeration of the two values true and false. A nullable bool adds a null to the set increasing the cardinality to 3.

Useful? Yes, making them a perfect data type to handle the undefined state besides the boolean result.

Nullable<bool> flag = null;

Or using the short form (T? = nullable):

bool? flag = null;

In Windows Powershell:

[nullable[bool]]$flag = $null

Note: extending the value set can change semantics (the meaning) with existing syntax (the form).

The following is not valid anymore because you cannot cast a nullable bool to a bool to evaluate the expression.

Is flag null or false?

if(!flag) 
{  
    Console.WriteLine("false"); 
} 

You need to be specific in the evaluation because squishing a set of 3 values to a set of 2 values in not possible without data loss.

if(flag == false) 
{  
    Console.WriteLine("false"); 
}