Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Tip/Trick

Use Nullable Types!

Rate me:
Please Sign up or sign in to vote.
4.80/5 (2 votes)
4 Feb 2013CPOL2 min read 18.6K   6   10
An intro to Nullable Types in C#.

Introduction

Familiar with '?' and '??' ? 

Seeing that some C# developers are not acquainted with nullable types. That is perhaps because they can be avoided - meaning you can "get along" without them.

However, being that the nullable types make the code more friendly and simpler to read. And, in some cases the functionality can be easier implemented.

I think it's worth a tip post.

Using Nullable Types in the code 

Basically, these are primitives that can have a null value, they can represent the range of values you are familiar with and an additional null value. Nullable types are instances of the System.Nullable<T> struct. 

Note: Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type, this is of course because Reference types already support the null value and they will work with the following code, using the ? char to identify the nullable attribute 

C#
// Define a double d and set d to be null
double? d = null;

// Now let's make a conditional assignment:

// Define a second double d2 and set it's value to be d
// unless d is null in which case set it to be Pi
double d2 = d ?? 3.141592653589793;   

You can use the property HasValue to check if it is not null: 

C#
int? num = null;
if (num.HasValue == true)
{
   System.Console.WriteLine("num = " + num.Value);
}
else
{
   System.Console.WriteLine("num = Null");
} 

Check out MSDN's Nullable Types article (VS2012 version): http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.110).aspx 

Points of Interest 

Note: The following code   

C#
...
DateTime? dt = new DateTime();
dt = null;
return dt.ToString();

will return String.Empty.

Note: Nested nullable types are not allowed. The following line will not compile:

C#
Nullable<Nullable<int>> n; 

Note: Use the Nullable<T>.GetValueOrDefault method to return either the assigned value, or the default value for the underlying type if the value is null, for example:

C#
int j = x.GetValueOrDefault(); 

GetType

Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type. 

C#
int? i = 5;
Type t = i.GetType();
Console.WriteLine(t.FullName); //"System.Int32" 

Boxing a Nullable Type

Nullable objects and their boxed counterpart can be tested for null: 

C#
bool? b = null;
object boxedB = b;
if (b == null)
{
  // True.
}
if (boxedB == null)
{
  // Also True.
}

Boxed nullable types fully support the functionality of the underlying type: 

C#
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(); 

Summary  

So, lets make the world a better place by using nullable types... 

History 

v1.0.0.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
United States United States
Senior dish washing consultant for over 25 years!

Comments and Discussions

 
GeneralThoughts Pin
PIEBALDconsult27-Apr-15 7:27
mvePIEBALDconsult27-Apr-15 7:27 
GeneralRe: Thoughts Pin
Joezer BH28-Apr-15 0:00
professionalJoezer BH28-Apr-15 0:00 
SuggestionA nice exaplanation, perhaps add some use cases Pin
Herbisaurus13-Aug-13 23:10
Herbisaurus13-Aug-13 23:10 
A nice exaplanation, perhaps add some use cases
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Joezer BH13-Aug-13 23:11
professionalJoezer BH13-Aug-13 23:11 
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Herbisaurus13-Aug-13 23:13
Herbisaurus13-Aug-13 23:13 
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Joezer BH13-Aug-13 23:14
professionalJoezer BH13-Aug-13 23:14 
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Herbisaurus13-Aug-13 23:15
Herbisaurus13-Aug-13 23:15 
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Joezer BH13-Aug-13 23:18
professionalJoezer BH13-Aug-13 23:18 
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Herbisaurus13-Aug-13 23:19
Herbisaurus13-Aug-13 23:19 
GeneralRe: A nice exaplanation, perhaps add some use cases Pin
Joezer BH13-Aug-13 23:19
professionalJoezer BH13-Aug-13 23:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.