vote buttons
0
1
beginner
0
intermediate
0
advanced
13-Nov-2014 02:00 UTC
K Bonneau
350

1 Answers

vote buttons
0

Boxing is converting a value type to an object type. Unboxing is converting an object to a value type.

int val = 1;
object obj = val; // Boxing
val = (int) obj; // Unboxing

This doesn't seem out of the ordinary so why special names have been given to these? These are special because both value types and reference/object types are stored in a very different manner and such cross assignment requires some work to be done. In the code example above the "obj" variable is a reference type so it can only refer to values which are stored in the heap, while "val" is stored on the stack (well not always but that requires its own post). Now while assigning val to obj i.e. obj = val, obj cannot refer to stack, so it has to make a copy of val and store it on the heap and then refer to it. This happens everytime we assign a value type value to an object. Similarly during unboxing, the value in the heap has to be copied onto the stack. This copying could cause performance issues if such operations are very frequent.


13-Nov-2014 02:00 UTC
K Bonneau
350