Boxing and Unboxing

Boxing

when a value is converted in to reference type then it called as Boxing

Boxing is 20 time costlier than normal initialization.


Syntax :

 int x =100;
Object obj =x;   //Boxing 

 

UnBoxing

If a value type is converted in to reference type is again convert in to value type is called as Un Boxing

  • Un Boxing is 4 times costlier than normal initialization.
  •   int y=Convert.Toint32(obj);  // Un Boxing
       

    Why use Boxing and Un Boxing

    These are very costlier process than normal initialization so these are avoided in maximum situation use only if required.

    To Print data types of given by value using var keyword

              
        using System;
    class Demo {
    	static void Main() {
    		Var i=10;
    		Console.WriteLine(i.GetType());
    		Var j=”scott”;
    		Console.WriteLine(j.GetType());
    		Var k=3.14m;
    		Console.WriteLine(k.GetType());
    		Var p=3.14;
    		Console.WriteLine(p.GetType());
    		Console.Read();
    	}
    }