Technical Articles

What is boxing and unboxing ?

0 0

Boxing

Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.

Unboxing

Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

For Example:

  1. / int (value type) is created on the Stack
  2. int stackVar = 12;
  3.  
  4. // Boxing = int is created on the Heap (reference type)
  5. object boxedVar = stackVar;
  6.  
  7. // Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
  8. int unBoxed = (int)boxedVar;

Another Example:
int x = 10;
string s = string.Format( "The value of x is {0}", x ); // x is boxed here

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
× How can I help you?