Community Pick: Many members of our community have endorsed this article.

Nullable Types

Published:
C# And Nullable Types

Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a database column for instance) and assigning a value will change the result.
Nullable type is applicable to primitive (known as value) types where data is stored in the stack and .NET Framework implicitly initializes them to their default values, even though the developer did not do that. Applying Nullable type to primitive types helps going round discomfort of looking for equivalent decisions like creating:

A boxed value type. This is not strongly-typed at compile-time, and involves doing a heap allocation for every type.
A class wrapper for the value type. This is strongly-typed, but still involves a heap allocation, and the you have to write the wrapper.
A struct wrapper that supports the concept of nullability. This is a good solution, but you have to write it yourself.

Nullable types can be declared in two ways:
System.Nullable<T> variable
                      T? variable

Open in new window

T is the underlying type of the variable. It can be a struct but cannot be reference type.

Any value type may be used as the basis for a nullable type. For example:

int? i = 10;
                      double? d1 = 3.14;
                      bool? flag = null;
                      char? letter = 'a';
                      int?[] arr = new int?[10];

Open in new window

Each instance of the above inherits two public read-only properties from Nullable type:
HasValue – bool type stating that variable contains a value
Value – variable underlying type value meaningful for the type (excluding null). Attempt to get the Value which has no value assigned (HasValue is false) will raise InvalidOperationException.
Testing for meaningful value can be done in two ways
int? x=null;
                      if(x.HasValue) {...} or
                      if(x!=null) {…}

Open in new window


Some notes about bool value type

When a bool variable is defined as nullable (i.e. bool? a) it can contains tree values: true, false and null. This make it unusable in if, for and while conditional constructions. The following will cause and error:

bool? x = null;
                      if(x) // will raise error

Open in new window

This is because in the case of a null value it is not clear what it means in this context – true or false. To avoid this, check HasValue first and then if it is true, cast to bool. Be aware that if cast is made when value is null an InvalidOperationException will be thrown.

Nullable Type Identification

Using GetType method or the is operator to obtain type information from Nullable variables at runtime will return underlying type not the Nullable type itself. This happens because GetType on a Nullable type will fire boxing to Object.
int? i = 10;
                      Console.WriteLine(i.GetType().FullName); //"System.Int32"

Open in new window

is operator operates on Nullable’s underlying  types and cannot be used to determine whether a variable is Nullable type.
int? i = 10;
                      Console.WriteLine(i is int); //"True"

Open in new window

Boxing

Nullable types can be boxed only if their value is non-null. When value is not null boxing is on the value type itself, not on System.Nullable(T) that wraps the value type.

Boxed nullable types can be tested for null:

bool? b = null;
                      object bB = b;
                      if (b == null)  {   /* True. */ }
                      if (bB == null) { /* Also true. */ }

Open in new window

Boxed nullable types has full functionality of the underlying type:

double? d = 44.4;
                      object iBoxed = d;
                      // Access IConvertible interface implemented by double.
                      IConvertible ic = (IConvertible)iBoxed;
                      int i = ic.ToInt32(null);
                      string str = ic.ToString();

Open in new window

Using Nullable type is very convenient in number of cases and reduce code writing. More info on the topic is available here
http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
0
4,124 Views

Comments (2)

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
You might want to make a note about what "boxing" is. I have a feeling that people who do not know about Nullable may also not know what the concept of "boxing" is  :)

Author

Commented:
In brief:
(un)boxing = conversion.
value -> reference type = boxing (wraps value in a Object)
reference -> value type = unboxing (extracts value from a Object)

Here's what Microsoft says about boxing 8-)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.