tags:

views:

35

answers:

1

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.

+3  A: 

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 ArrayList of integers, you'd have to box them first because ArrayList only works with objects).

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 (or string.Format) which takes the arguments as objects. For example:

int n = 1234;
Console.WriteLine("A number: {0}", n);

The integer n is boxed to a object reference in order to be passed to the Console.WriteLine method.

Dean Harding