DEV Community

Haris Iftikhar
Haris Iftikhar

Posted on • Updated on

Boxing Vs. Unboxing in C#

Boxing:
It converts a value type (int, char, etc.), to a reference type (object).
Simple terms: To convert a value to an object type.
Boxing is an implicit conversion process.
Here, the value stored on the stack is copied to the object stored on the heap.

Programming example (with a hard-coded value):
Programming Example

Programming Example (using Convert.ToInt32(Console.ReadLine())):
Programming Example

Unboxing:
It converts a reference type (object) back to a value type (int, char, etc.).
Simple terms: To convert an object type back to a value type.
Unboxing is an explicit conversion process.
The object stored on the heap is copied to the value stored on the stack.

Programming Example (with a hard-coded value):
Image description

Programming Example (using Convert.ToInt32(Console.ReadLine())):
Image description

Top comments (0)