Member-only story

Boxing and Unboxing in C#

Shahzad Aslam
2 min readApr 9, 2024

--

The Boxing and unboxing is the process of the conversion of value types to reference types.

Boxing and Unboxing in C#

1. Boxing:

When you convert value type into reference type. It is called boxing.

In the example below, the intValue is int type (value type) and it convert into object Which is reference type.

Boxing involves the creation of a new object on the heap, which can lead to a performance overhead. It’s essential to be mindful of boxing when working with performance-sensitive code.

int intValue = 42;
object boxedValue = intValue; // Boxing
Console.Write("After boxing value is : {0}", boxedValue);

Output

After boxing value is : 42

2. Unboxing:

When you convert again back reference type to value type. It is called unboxing.

In the example below, The boxedValue related to reference type (object). When we convert it back to value type (int). It is called unboxing.

Caution:

When you do a wrong boxing. An InvalidCastException error will come.

When you convert a string into integer this will give you a runtime exception. In below example.

int unboxedValue =…

--

--

Shahzad Aslam
Shahzad Aslam

Written by Shahzad Aslam

Welcome to c-sharptutorial.com. I am Shahzad Aslam. I am the founder of c-sharptutorial.com. I'm currently living near Islamabad, Pakistan.

No responses yet