All Type Coding

Search Here

Boxing and UnBoxing in c#.

Boxing is the process of converting a value type to the type object 
C# allows us to convert a Value Type to a Reference Type, and again to Value Types . The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.
Boxing
for example:
int a= 1;
Object b= a; //Boxing

Here we created a variable a  Value Type type and assigned a value to a 
The next line , we created an instance of Object and assign the value of a  to b.
Now we saw converting a value of a Value Type into a value of a corresponding Reference Type . These types of operation is called Boxing.

UnBoxing

  1: int a  = 1;
  2: Object ba  ;     //Boxing
  3: int c = (int)b;    //Unboxing

The first and second  two line shows how to Box a Value Type . The next line (int c = (int) b) shows extracts the Value Type from the Object . That is converting a value of a Reference Type into a value of a Value Type. This operation is called UnBoxing.

No comments :

Post a Comment