Wednesday, 28 March 2012

How to Handle null value on Valuetypes?


Yes, By default structure type like int,double,float,double,datetime…are can’t handle null value. and gives an complier error. So From .net 2.0 onwords we have the concept of Nullable types
Syntax:
            StructureType?  Varibale=null;
Ex:
   int b = null;    ---complier error
complier error: can’t implict convert value type to non-nullable type.

   int? b = null;    ----complied succefully.

We have one more Structure is Nullable<T> which has Properites and methods like

       public Nullable(T value);
       public bool HasValue { get; }
       public T Value { get; }
       public static explicit Operator T(T? value);
       public static implicit Operator T?(T value);
       public T GetValueOrDefault();
       public T GetValueOrDefault(T defaultValue);
  Now how to use them:
Demo:
int? b =null;      or // int? b = new int(); constructor of NullableType

if (b.HasValue == true)
{
Console.Write("value is"+ b.Value);
}
else
{
 Console.Write(b.GetValueOrDefault()); // default value of int


Console.Write(b.GetValueOrDefault(407)); // default value of our requirement.
}        
Console.ReadKey();


What is implict and Explict Castings?
Demo:

        static void Main()
        {
            int? b = 41;    
            int? c;
            
            if (b.HasValue == true)
            {                
                c =b;   // implict type casting
                Console.WriteLine(c);
            }
            else
            {
             Console.Write(b.GetValueOrDefault()); // default value of int
             Console.WriteLine();
    Console.Write(b.GetValueOrDefault(407)); // default value of our requirement.
            }
            
Note: Every primetive type has it’s own default value.

No comments:

Post a Comment