Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Nullable Types

Published on
9,525 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
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Join & Write a Comment

This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month