26 October 2011

Nullable value types

Some times, we came to a situation where we need to put null value into a Integer variable, or into any other value types( We can take an example of database operations, it may possible that even Bool(bit) column in table contains null value.)

In such situation Nullable types comes into picture.

What exactly Nullable types are:

  • Its an instance of System.Nullable struct
  • It just represents a value type which even can be assigned to a null value.

Example:
public class NullableTypesTest
{
    static void Main()
    {
        Nullable<int> IntPriNumber=null;
        if (IntPriNumber.HasValue == true)
        {
            System.Console.WriteLine("Varibale has value and its "+IntPriNumber.Value);
        }
        else
        {
            System.Console.WriteLine("Varibale dont have a value");
        }
}

Some points about Nullable types:

  • We cannot create Nullable types based on reference types.
  • Nullable types have some important 
    • properties like 
      • HasValue - returns true/false indicating variable contains value or not.
      • Value - return the value it contains.
    • methods like
      • GetValueOrDefault() - return default value in case of variable contains null value,
        Example
         
        
             Nullable<int> x=55;
             
             //Print 55
             System.Console.WriteLine(x.GetValueOrDefault());
             
             Nullable<int> y=null;
             
             //Print 0
             System.Console.WriteLine(y.GetValueOrDefault());
        
  • Alternative way of defining nullable types is
    T? variable=some value
    where T is a value type.
    Example
    int? temp=55