When should one use nullable types in c#?

In the .Net framework there are two data types: value type and reference types. A string is a reference type, it can be assigned with a null value. A reference type is a reference to a location in memory. Examples of built in reference types in C# are: objectdynamic, and string.

These are value types:


Value types can be assigned a value directly. When you think of the Boolean value type, you probably think it is either true or false and this is a correct assumption. However, things in the real world are not so clear cut. When we are dealing with humans, who make mistakes, and databases where errors have not been realized our Boolean may end up throwing null reference errors at production.

To overcome this issue, Microsoft introduced the nullable type. The syntax for nullable type is Nullable<T>. So while,

Nullable<Boolean> trueTest = null; will not throw an exception,

Boolean trueTest = null; will throw an exception.

This allows us to handle instances a null value was inserted into our database and we are expecting an integer. So now, using the shorthand for a nullable type:

int? myInt = null; is a completely acceptable state.

We could even go further and set a default value of a non-nullable type by using the null-coalescing operator??, in conjunction with our nullable type.

An example of the null-coalescing operator would be to assign a value to an non-nullable value type based on a value of the nullable type: 

int? a = null; int b = a ?? -1;.

In the example, since x is null, the result value of b is -1.

You can read more about nullable types and their characteristics here.