Monday, 24 February 2014

Boxing and Unboxing


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.

Real Life Example
int i = 10;
ArrayList arrlst = new ArrayList();

//ArrayList contains object type value

//So, int i is being created on heap

arrlst.Add(i); // Boxing occurs automatically

int j = (int)arrlst[0]; // Unboxing occurs

No comments:

Post a Comment

back to top