Boxing & Unboxing – C#

Boxing and unboxing are the most important concepts you always get asked in your interviews. Actually, it’s really easy to understand, and simply refers to the allocation of a value type (e.g. int, char, etc.) on the heap rather than the stack.

C# Type System contains three types:

  1. Value Types
  2. Reference Types
  3. Pointer Types

C# allows us to convert a Value Type to a Reference Type, and back again to Value Types.

The operation of Converting a Value Type to a Reference Type is called Boxing and the reverse operation is called Unboxing.

Value types are stored in Stack.

Reference types are stored in Heap.

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.

 

 

int Val = 1;

Object Obj = Val; //Boxing

 

The first line we created a Value Type Val and assigned a value to Val. The second line, we created an instance of Object Obj and assign the value of Val to Obj. From the above operation (Object Obj = i ) we saw converting a value of a Value Type into a value of a corresponding Reference Type. These types of operation are called Boxing.

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.

 

                int Val = 1;

Object Obj = Val; //Boxing

int i = (int)Obj; //Unboxing

 

 

The first two lines show how to Box a Value Type. The next line (int i = (int) Obj) shows extracts the Value Type from the Object. That is converting a value of a Reference Type into a value of a Value Type. This operation is called Unboxing.

Basic Example

// int (value type) is created on the Stack
int stackVar = 12;

// Boxing = int is created on the Heap (reference type)
object boxedVar = stackVar;

// Unboxing = boxed int is unboxed from the heap and assigned to an int stack variable
int unBoxed = (int)boxedVar;

 

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

 

What do you think?

I hope you will enjoy the tips while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

 

Print Friendly, PDF & Email
Spread the love

3 thoughts on “Boxing & Unboxing – C#

Leave a Reply

Your email address will not be published. Required fields are marked *