Thursday, October 27, 2005

Nullable Types in C# : .Net says hello to null values

How often have we rued over not able to store a null value in a Int variable in C# ? Many programmers,especially ones those deal with databases that contain optionally fields must have often wished to store null values in the datatype.

Come this November, and all this greivances come to an end. With the newest standards of C# 2.0, there will be support of nullable data types.

Nullable data types can represent all the values of the underlying type and additional null value.A nullable datatype can be declared as follows

datatype? variableName;

For Example:
int? a;

The nullable version datatype is actually a structure that combines a value type with a flag to indicate whether the value is null. Additionally, a nullable type has two publicly readable properties, HasValue and value. HasValue is a bool that is true if there is a value stored; otherwise, it is false if the variable is null. If HasValue is true, you can get the value of the variable. If it is false and you attempt to get the value, then an exception will be thrown.

Casting To a regular datatype

Nullable datatype can be easily casted to regular dataype.In fact, implicit conversions are built in for converting between a nullable and non-nullable variable of the same type.Of course, an exception will be raised if you try to assign a null value to non-nullable datatype.

Operations on Nullable data type.

Consider following code.

int? a=2;
int? b=3;
int? c=a+b;

The above code would just like normal regular datatype as both variables contain values.But consider case where either of 'a' or 'b' is null. In such a case, where either of operand is null , the result of operation too would be null.

Null Coalescing : Removing Nullability

C# 2.0 introduces a new operator called the null coalescing operator denoted by double question marks (??). The null coalescing operator takes 2 arguments; a nullable type to the left and the given nullable type’s underlying type on the right. If the instance is null, the value on the right is returned otherwise the nullable instance value is returned. Examine the example below

int? a=null;
int? result=a??2;


In above example, null will be returned to variable 'result'.If variable 'a' had non-null value , then that value would have been returned to variable 'result'.

Nice feature right ? Its just one among the numerous features .Net 2005 is bringing along.
Anyways me signing off.