1Boxing and Unboxing in C#
Hi friends, in this article we will learn boxing and unboxing in C#. Boxing converts a value type into an object reference. Unboxing retrieves the original value type from that object. These operations are useful when working with APIs and collections that store values as objects. Understanding them also helps us avoid unnecessary memory allocations and runtime errors.
2Think About Packing a Product
Imagine you have a small product and need to place it inside a common shipping box. The product is still the same, but now it is packed inside a general container.
Boxing works similarly: an integer value is wrapped inside an object. Unboxing is like opening the box and retrieving the original integer.
3How Boxing and Unboxing Work
1. Boxing
Boxing converts a value type, such as int, into object or another compatible reference type. The runtime creates an object containing a copy of the value.
2. Unboxing
Unboxing extracts the value type from the boxed object. You must cast it to the correct value type.
3. Important points
- Boxing is an implicit conversion.
- Unboxing requires an explicit cast.
- An incorrect unboxing type causes InvalidCastException.
- Unboxing a null object into a non-nullable value type causes NullReferenceException.
| Operation | Conversion |
|---|---|
| Boxing | int → object |
| Unboxing | object → int |
4Let's Write a C# Program
We will box an integer into an object, then unbox it back into an integer.
using System;
class Program
{
static void Main()
{
// Original value type
int number = 100;
// Boxing: int to object
object boxedValue = number;
Console.WriteLine("Boxed value: " + boxedValue);
// Unboxing: object to int
int result = (int)boxedValue;
Console.WriteLine("Unboxed value: " + result);
}
}
5Check the Program Result
The integer is boxed into an object and then unboxed back to an int. Both display the same value.
Boxed value: 100 Unboxed value: 100
6Watch Boxing Happen Step by Step
7Quick Revision
Boxing wraps a value type inside an object. Unboxing retrieves the original value type through an explicit cast. Both operations are handled by the .NET runtime.
- Boxing: value type to object.
- Unboxing: object back to value type.
- Use generics to reduce unnecessary boxing.
8Interview Questions to Practise
What is boxing in C#?
Answer Boxing converts a value type into object or a compatible reference type by creating an object containing the value.
What is unboxing?
Answer Unboxing extracts the original value type from a boxed object using an explicit cast.
Is boxing implicit or explicit?
Answer Boxing is implicit. C# automatically converts a value type to object when needed.
What happens if the unboxing type is incorrect?
Answer The runtime throws InvalidCastException because the requested type does not match the boxed value type.
How can we avoid unnecessary boxing?
Answer Use generic collections such as List<int> instead of non-generic collections that store values as object.