Tuesday, May 26, 2009

Nullable Types in C#

In 1.x days we cannot assign a null value to value types.Assigning a null value will throw an error.

int mobile = null; //Will throw an error

This is an inconvenience whenever we are retrieving a value from a database that can allow nulls and assigning to .net variable. But this inconvenience is no more now because of the Nullable types. A nullable type can be declared similar to normal variable but with ? modifier at the end of keyword.

i.e., a valid nullable type declaration will be,

int? mobile = null;

Alternatively we can declare like,

Nullable mobile = null;

int? will be the shorthand notation of Nullable.

Things to know about Nullable Types:

Nullabe types are instances of System.Nullable struct.Nullable type structure differs from normal type by having flag extra to indicate whether it contain null value.Additional it have 2 other properties which we will be looking in detail in this article.

Working with Nullable Types:
How to retrieve the value from a nullable type?

As we discussed early it has 2 other property called Has Value and Value.
Value:

This property is a read only property which retrieves the value associated with the type.This property will throw an exception when it is accessed with a null value.

int? mobile = null;
int my mobile = mobile.Value;

The above line will throw a exception,

"Invalid operation exception"

Nullable object should have value.

HasValue:

This property returns a Boolean indicating whether the variable contains a value.
So the above exception can be prevented by writing the code like,

if (mobile.HasValue)
{
int mymobile = mobile.Value;
}

Consider a situation like,

int? n1 = 2;
int n2 = 3;

Now what will be output type of (n1*n2) ?

int sum = n1 * n2;

The above operation will throw an error.

This operation gives a result which a nullable type can hold and thus it can be assigned to a variable like,

int? sum = n1 * n2;

We can call these operators as Lifted operator’s i.e., it will lift the non nullable type to nullable type. Assigning null to any of the above variable will result null. The same behavior applies to + and – operators.

Getting a default value with Nullable Types:

int? n1 = null;

int n2 = 3;

(n1 ?? 10) will return the value 10.This will be useful when we are fetching a allow null field from database and assigning to a non nullable type or it can be used in a operation like below. Hence we can assign a default value.

int product = (n1 ?? 10) * n2;

Now product will hold 30 since (n1 ?? 10) will return 10.

Note:

We cannot create nullable types with reference types.

No comments: