Go Premium for a chance to win a PS4. Enter to Win


Nullable Types

Published on
9,569 Points
Last Modified:
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


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
Author:Ivo Stoykov
LVL 75

Expert Comment

by:käµfm³d 👽
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  :)
LVL 22

Author Comment

by:Ivo Stoykov
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-)

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Join & Write a Comment

This Micro Tutorial will teach you how to add a cinematic look to any film or video out there. There are very few simple steps that you will follow to do so. This will be demonstrated using Adobe Premiere Pro CS6.
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an anti-spam), the admin…
Suggested Courses

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month