"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Tuesday, February 14, 2012

Boxing-Unboxing Variables

Hi *.*,


Boxing-Unboxing Variables, its a common interview question.In our everyday programming we came across this.Anyway for the unknows, here it goes...



Boxing:    Boxing is process of converting valueType variable to Referance Type veriable at runtime.


Unboxing:    Unboxing is a process of converting referance type to value type variable at run time
Unboxing is an explicit operation.


What happened in backend.


Value type is stored in Stacks
Reference type is stored in Heap


So boxing.


Values shifted Stacks to Heap and vice versa.



If u had any trouble just ask, Happy to help u :) Stay Tune... Have a nice day... 'N happy Coding :)

2 comments:

a said...

i didnt understood..pls give an example.

SImplyAsp said...

ya sure,Here she goes...

Int32 x = 10;
object o = x ; // Implicit boxing
Console.WriteLine("The Object o = {0}",o); // prints out 10
//-----------------------------------------------------------
Int32 x = 10;
object o = (object) x; // Explicit Boxing
Console.WriteLine("The object o = {0}",o); // prints out 10

UnBoxing:Converting Refrence type to Value Type is called unboxing.
---------
example:
Int32 x = 5;
object o = x; // Implicit Boxing
x = o; // Implicit UnBoxing