Are these boxing/unboxing examples
Asked Answered
S

4

5

Are 2 and 3 boxing/unboxing examples?

1) The documentation example:

int i = 123;
object iBoxed = i;
i = (int) iBoxed;

2: Is the boxing/unboxing as well?

int i = 123;
object iBoxed = i;
i = Int32.Parse(iBoxed.ToString());

3: Is the boxing/unboxing as well?

int i = 123;
object iBoxed = i;
i = Convert.ToInt32(iBoxed);

I assume that in all examples technically happens the same.

  1. A value type is created on the stack
  2. A reference is created on the stack, the value is copied to the heap.
  3. The heap value is copied to the reference. The reference gets deleted.

So I guess 2 und 3 are examples for boxing/unboxing?

Scully answered 6/6, 2011 at 8:11 Comment(1)
i think so, since you put int in an object "box" and then you retireve it form that box. The idea behind box and unbox is to change a value type to a reference type and backVendible
S
7

In all three examples:

iBoxed is a boxed copy of i.

In example 2: There is no unboxing involved here, as ToString is a virtual method that will finally resolve to int.ToString, which will then be parsed by int.Parse, returning a non-boxed int on the stack.

In example 3: iBoxed will get unboxed in the body of the method Convert.ToInt32 and returned as a non-boxed integer, on the stack again.

Squatter answered 6/6, 2011 at 8:20 Comment(1)
I fixed example 2, which didn't compile anyway.Scully
A
2

The second example is boxing but not unboxing. The int.parse won't compile because it expects a string and iBoxed is an object. I think you are mixing the concepts of boxing and conversion. Boxing is really about taking a value type ie POD as they say in C and treating it as reference unboxing is the ability to extract that same value type out of its container.

Ex 2. Fixed

int i = 123;  // Assigment 
object iBoxed = i ; // This is boxing 
i = int.parse(iBoxed.toString());  //This is unboxing but only for the twostring method the assignment is a value type copy. 
Afro answered 6/6, 2011 at 8:20 Comment(0)
A
1

It's object iBoxed = i which do the boxing.

Example 2 wont work since int.Parse expects a string

Amplexicaul answered 6/6, 2011 at 8:19 Comment(0)
K
0

In all your examples, the value type i is being converted to an object. This is the definition of boxing according to MSDN. Boxing could also be done by:

object boxed = (object)i;

The unboxing is the conversion of the object back to a value type.
Example 1 is unboxing

Example 2 will fail to compile because Parse expects a string argument but would be unboxing if you did iBoxed.ToString()

Example 3 i suspect is not unboxing because the Convert method will just return the value that you pass in.

Its worth being aware of the performance hit of boxing and unboxing. It is more expensive than normal assignment.

Kessel answered 6/6, 2011 at 8:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.