Nullable types were a great addition to C#. They were added way back in C# 2.0 but there is still confusion on how to work with them for some developers, especially junior developers. In this post, I will provide an overview of the most efficient ways to work with them and use them correctly.
What are Nullable Types?
Nullable types are simply a type in the common type system (CTS) that can either have a value or be null. This is supported for most of the basic types in the .NET framework such as integer, GUID, double, decimal, single, DateTime, etc. I find it most helpful to think of nullable types as a wrapper around a type. I will explain why.
How are Nullable Types Used?
Nullable types must be instantiated with the question mark identifier.
Listing 1.1 – Nullable type example
int? counter;
The value of a nullable variable is actually stored in the Value property. Remember what I said about nullable types being a wrapper around a type?
Listing 1.2 – Retrieving the value of a nullable variable
Console.WriteLine($"Counter: {counter.Value}");
Before accessing that value, however, you should always check that it has a value with the HasValue property. Since the variable is nullable, you will receive an InvalidOperationException if you try to access the Value property and it is null.
Listing 1.3 – Testing the value of a nullable variable
if (counter.HasValue) { Console.WriteLine($"Counter: {counter.Value}"); }
Finally, because the Value property is read-only when assigning a value to the nullable variable, it is assigned directly to the variable, not the Value property.
Listing 1.4 – Assigning a value to a nullable variable
counter = 12;
Conclusion
Nullable types are a cleaner way to write code when used appropriately. They help you avoid testing for default values in your applications which is a definite anti-pattern. Instead, they offer a much cleaner way to perform the same type of function. They offer a layer of simplicity and are simple to use after understanding the concepts discussed above.