Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Nullable Types in C# 2.0

Posted by Ravi Varma Thumati on May 4, 2009

Introduction:

The .NET Framework 2.0 introduced the Nullable types which allow the developer to assign null values to the primitive type variables. In this article we will see how you can use the Nullable types.

What are Nullable types?

The Nullable types allow you to assign the null values to the primitive types. These primitive types include Int32, Int16, Double, Float etc. Take a look at the simple example below which assigns a null value to Int32 variable.

Nullable<Int32> i = null;

Nullable represents an object whose underlying type is a value type. Microsoft thought that using the syntax above is quite cumbersome for the developers and hence introduced a much simplified syntax for declaring nullable types.

Int32? i = null; // This is same as int?

int? j = null; // This is same as Int32

// And both are same as Nullable<Int32> z = null

As, you might have noticed that, nullable types requires the ‘?‘ after the type; If you view the Intermediate Language generated by the above two lines you will notice that both the lines will map to the Nullable<Int32>.

Assigning Nullable Type Variables:

Assigning the values to the Nullable type variables is same as assigning the value to the Non-Nullable primitive types. Take a look at the following code.

Int32? a = null;

Console.WriteLine(a); // prints nothing

a = 5;

Console.WriteLine(a); // prints 5

The Nullable types also have a Value property which enables the user to return the value of the variable in the primitive type. Check out the code below which demonstrates two techniques to assign the value to the variable.

int b = a.Value;

int c = (int) a;

The IL code generated for both the lines is exactly the same and they will both map to the Nullable<Int32>.

Nullable Types are still the Value Types:

Even though you can assign a null value to the Nullable type variable this does not means that the Nullable type variable will start behaving as the reference type variable. Check out the code below which demonstrates this scenario.

int? a = 10;

int? b = a;

b++;

Console.WriteLine(“a is {0}”,a); // still prints 10

Console.WriteLine(“b is {0}”,b); // prints 11

As, as can see from the code above the Nullable type variable behave exactly the same as the value type variable.

Returning Null Values from the Database:

Suppose that you have a column in the database which contains Int32 values but also allows the null values. A common way to access such a column will be using the following code.

private static void DisplayNoOfPets()

{

string query = “SELECT NoOfPets FROM Users WHERE UserID = 3”;

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlCommand myCommand = new SqlCommand(query, myConnection);

myConnection.Open();

// The line below will throw an exception since null will be returned

int noOfPets = (int) myCommand.ExecuteScalar();

myConnection.Close();

}

Unfortunately, if the UserID = 3 does not contain any pets it will contain null and the InvalidCastException will be thrown. In order to get this working you will need to introduce the Nullable type which will support the null values. Take a look at the code below which uses the Nullable type.

private static void DisplayNoOfPets()

{

string query = “SELECT NoOfPets FROM Users WHERE UserID = 3”;

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlCommand myCommand = new SqlCommand(query, myConnection);

myConnection.Open();

int? noOfPets = myCommand.ExecuteScalar() as Int32?;

myConnection.Close();

}

Now, instead of throwing the exception the noOfPets variable will contain the null value.

The Null-Coalescing Operator:

The null-coalescing operator is denoted by (??) and takes two parameters. If the operand on the left hand side is not null then it will be returned otherwise the the operand on the right hand side will be returned. Let’s take a look at the small example.

string value = null;

Console.WriteLine(value ?? “It was null”); // It was null will be printed

Think about the code above for a moment. The code above is the smaller version of the following code.

 string value = null;

if (value == null)

Console.WriteLine(“It was null”);

else Console.WriteLine(value);

Here is another small example of the null-coalescing operator.

int? a = null;

int? b = a ?? 50;

Console.WriteLine(b); // This will print 50

Conclusion:

In this article we demonstrated the new Nullable type which is introduced in the .NET Framework 2.0. The Nullable type along with the Null-Coalescing operator helps the developer to design better applications. The new syntax of the features also allows the developers to express their thoughts in a more meaningful way.

Advertisements

2 Responses to “Nullable Types in C# 2.0”

  1. I do know this isn’t exactly on subject, but i’ve a web page using the identical program as well and i am getting troubles with my feedback displaying. is there a setting i’m missing? it’s doable you could help me out? thanx.

  2. Really instructive and excellent complex body part of subject matter, now that’s user friendly (:.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: