Monday, March 19, 2007

Nullable datatypes in C#

       In C# 2.0 there is a special datatypes called Nullable datatypes. You can assign null to them. Here is some basic information regarding Nullable data types.

        You can make any value types to nullable data types by writing as shown below.

public int? intA = null;

Fig - (1) Declaring integer data types so it can have null as value.

        Fig (1) shows how to declare data types do that it can have null as value. Now to check that if intA has non null value or it is null, you can use HasValue property.        

// Check HasValue method
if (intA.HasValue)
          Console.WriteLine("intA is not null");
          Console.WriteLine("intA is null.");

Fig - (2) Check that nullable type has non null value.

         As desribe above HasValue property returnd true if nullable types has non null value else returns false. To access the value of nullable types, "value" property is used as shown here, intA.Value. You can use nullable types in arithematic operation in same manner you are using integer (or any) types. If you are using them in Summation and if any of nullable type has value null than you will get null as result regardless of other variables value.

        Operator ?? is used check nullable value against null as shown below,

// Check ?? operator
int d = intA ?? -1;

Fig - (3) Check against null using ??.

       If  intA is null than d = -1, else d = value of intA which is intA.Value. So for default assignment you can use ?? instead of checking by HasValue property.

      I looked in to the IL for nullable data types and simple data types and here is what i found.

.field public int32 intB

Fig - (4) IL generated for simple integer.

.field public valuetype [mscorlib]System.Nullable`1<int32> intA

Fig - (5) IL generated for nullable integer.

      You can see in IL that "Nullable`1" attributes is added so that CLR can identify the nullable datatypes.

     I further look in to the Boxing of Nullable types.

int? i = 44;
// Boxing
object iBoxed = i; // iBoxed contains a boxed int.
// UnBoxing
int? i2 = (int?)iBoxed;

Fig - (6) Boxing and UnBoxing for Nullable types.

           One interested thing here is, Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, then, instead of boxing, the object reference is simply assigned to null. The boxed object for nullable types and non nullable types are exactly same.

Happy Programming!

1 comment:

Anjum Rizwi said...

Thank you Raja,

It is very helpfule for me.