Back to Basics – Nullable Value Type
Back to Basics – Nullable Value Type
In the following posts
I’m going to describe
basic tools which every
developer needs to
know. In today’s post
I’m going to explain
what is a
Nullable value type and how
to use it in your code.
What are Nullable Value Types?
Nullable value types are an instances of the Nullable<T> struct.
The nullable value type can hold the all the values that its underlining value type holds
and a null value. The main reason for this type came from the use of databases.
In databases, data can be null (or if you prefer DBNull) and when the developers
retrieved the null value instead of a value type they expected a problem was raised.
What can you do with the database null value? should you use the default value for
the value type which can cause logical or business errors? should you use minimum
value to indicate null? Using the nullable value type helped to remove those questions.
The use of nullable value type can grantee a simple and clean way to hold a value type
even if it was returned from the database as null.
How to Use Nullable Value Types?
There are two ways to create a nullable value type:
- By using the ? type modifier -
- By using the Nullable<T> struct -
The nullable value type has two properties that can be used by the developer:
- HasValue – returns true if the nullable value type holds a value.
Returns false if the nullable value type holds null. - Value – returns the value that the nullable value types holds.
The property should always be accessed after you check if the nullable value
type has a value otherwise an InvalidOperationException exception will be thrown.
Another thing to know about a nullable value type is the GetValueOrDefault method.
That method returns the value inside of the nullable value type or the default value for the
underlining value type if the nullable value type is null.
An example of how to read a value from a nullable value type can look like:
int? someNumber = null;
if (someNumber.HasValue)
{
Console.WriteLine("the value is {0}",
someNumber.Value);
}
else
{
Console.WriteLine("There is no value");
}
The code above will produce the “There is no value” sentence in the console.
A restriction that needs to be followed is that you can’t have nested nullable value types.
The following code won’t even compile:
Nullable<Nullable<int>> someNumber;
Summary
The post introduced the concept of nullable value types.
You should use the type on members that are being returned from a database columns
which can hold null values. The use of the nullable value types is simple and straight forward.