[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More


Nullable Types

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

Build an E-Commerce Site with Angular 5

Learn how to build an E-Commerce site with Angular 5, a JavaScript framework used by developers to build web, desktop, and mobile applications.

Please check the video also in regards to recovery of deleted emails from office 365 admin center and through the MFCMAPI tool. I have mentioned each and every step with the proper steps that need to be taken care of.
Microsoft Office 365 Backup and Restore Solution by SysTools to export Office 365 mailbox to PST / EML file format on Windows OS. On Mac, tool backup O365 to PST / MBOX / MSG / EML / EMLX file formats. Not only this, restore option helps to import s…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month