Nullable Types in .NET Framework




- April 20, 2015

Rest of the Story:

Within the .NET Framework data types such as Boolean can either be true or false. Right? Well, with the release of 2.0 Framework it has been possible to create nullable data types. A nullable type can represent all the values of the underlying type plus empty (or undefined). In the case of our Boolean it would be True/False and Nothing.

It is only possible to create a nullable types Nullable(Of T) for value types since the default value for reference types is already nothing. The following types are valid as nullable: Boolean, Byte, Int16, Int32, Int64, Single, Double, Decimal, DateTime. The following examples show examples on how to create a nullable variable type:

Dim success as New Nullable(Of Boolean)()
Dim customerId as New Nullable(Of Integer)()
With the release of .NET 3.5 it is also possible to use the short form versions:
Dim success as Boolean? Dim customerId as Integer?
In C#

bool? success;
int? customerId;

To check of a nullable type as a value it is possible to use the HasValue or Value properties. Use the System.Nullable.GetValueOrDefault property return either the assigned value, or the default value for the underlying type.
If customerId.HasValue Then do something End If
If assigning a nullable type to a non-nullable type you must cast operator is necessary. For example:
int newCustomerId = (int)customerId; // in C#
Nullable types can be useful when dealing with NULL values from a database query however they are not the same. That is to say that DBNULL value is not the same as Nothing. When returning data from the database the following code will be necessary:
int? customerId = null;
if (!DBNULL.Value.Equals(reader[“CustomerId”])){ // this code converts the DBNULL to a c# null
customerId = (int)reader[“CustomerId”];
}