By Definition we know that
Boxing – Converts value-type TO reference type. Stored on heap.
UnBoxing – Converts reference type TO value-type. Stored on stack.
But why should I convert a value type to reference type or push my variable from stack to heap or from heap to stack.
What are advantages or disadvantages of doing this.
what we get by doing this. Whats the use of this.
Which situation we want to convert value type to reference type or to push variable from stack to heap. What we want to achieve with heap there which we can not with stack or in unBoxing with stack which we can not with heap.
I know this typical example
Int32 x = 10;
object o = x ; // Implicit boxing
Int32 y = 10;
object obj = (object) y; // Explicit Boxing
x = o; // Implicit UnBoxing
please give some other.
In C#, you usually don’t know when boxing is happening and at least with .NET 2.0 generics, boxing is not needed as often (in .NET 1.x, if you wanted to have an
ArrayListof integers, you’d have to box them first becauseArrayListonly works withobjects).But the main place you’ll be using boxing is in function calls that accept only objects. The most obvious example of that is
Console.WriteLine(orstring.Format) which takes the arguments asobjects. For example:The integer
nis boxed to aobjectreference in order to be passed to theConsole.WriteLinemethod.