Wednesday, 5 February 2014

Boxing and Unboxing in c#

Boxing and unboxing is a  essential concept in .NET’s type system.
With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object.
Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object.
Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation.

using System; 
 
class MainClass 
  public static void Main() { 
    int x; 
    object obj; 
 
    x = 10
    obj = x; // box x into an object 
 
    int y = (int)obj; // unbox obj into an int 
    Console.WriteLine(y)
  
}
 Output:
10 

Boxing occurs when passing values
 
using System; 
 
class MainClass 
  public static void Main() { 
    int x; 
    
    x = 10
    Console.WriteLine("Here is x: " + x)
 
    // x is automatically boxed when passed to sqr() 
    x = sqr(x)
    Console.WriteLine("Here is x squared: " + x)
  
 
  static int sqr(object o) { 
    return (int)o * (int)o; 
  
}
 
 Output:
 
Here is x: 10
Here is x squared: 100
 
 

No comments:

Post a Comment