Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between Boxing and Unboxing in C#
Boxing converts a value type to an object type, whereas unboxing converts an object type back to the value type. These operations are fundamental concepts in C# that involve moving data between the stack and heap memory.
Boxing occurs implicitly when you assign a value type to an object variable, while unboxing requires explicit casting and can throw exceptions if the types don't match.
Syntax
Following is the syntax for boxing (implicit conversion) −
object boxedValue = valueType;
Following is the syntax for unboxing (explicit conversion) −
ValueType unboxedValue = (ValueType)boxedObject;
How Boxing Works
In boxing, the value stored on the stack is copied to a new object stored on heap memory. This creates a reference type wrapper around the value type.
Example
using System;
class Program {
public static void Main() {
int a = 10;
Console.WriteLine("Original value: " + a);
Console.WriteLine("Type: " + a.GetType());
// Boxing - implicit conversion
object obj = a;
Console.WriteLine("Boxed value: " + obj);
Console.WriteLine("Type: " + obj.GetType());
// Modify original variable
a = 20;
Console.WriteLine("After modifying original:");
Console.WriteLine("Original value: " + a);
Console.WriteLine("Boxed value: " + obj);
}
}
The output of the above code is −
Original value: 10 Type: System.Int32 Boxed value: 10 Type: System.Int32 After modifying original: Original value: 20 Boxed value: 10
How Unboxing Works
In unboxing, the object's value stored on heap memory is copied to a value type variable on the stack. This requires explicit casting and type checking.
Example
using System;
class Program {
public static void Main() {
int original = 42;
// Boxing
object boxed = original;
Console.WriteLine("Boxed: " + boxed);
// Unboxing - explicit conversion
int unboxed = (int)boxed;
Console.WriteLine("Unboxed: " + unboxed);
// Demonstrating type safety
try {
double wrongType = (double)boxed; // This will throw an exception
}
catch (InvalidCastException ex) {
Console.WriteLine("Error: " + ex.Message);
}
}
}
The output of the above code is −
Boxed: 42 Unboxed: 42 Error: Unable to cast object of type 'System.Int32' to type 'System.Double'.
Comparison
| Aspect | Boxing | Unboxing |
|---|---|---|
| Conversion Type | Implicit | Explicit (casting required) |
| Memory Movement | Stack to Heap | Heap to Stack |
| Performance | Slower due to heap allocation | Slower due to type checking |
| Exception Risk | None | InvalidCastException if types don't match |
Common Use Cases
Example
using System;
using System.Collections;
class Program {
public static void Main() {
// ArrayList stores objects, so boxing occurs
ArrayList list = new ArrayList();
// Boxing happens here
list.Add(10);
list.Add(20);
list.Add(30);
Console.WriteLine("Values in ArrayList:");
foreach (object item in list) {
// Unboxing to perform arithmetic
int value = (int)item;
Console.WriteLine("Value: " + value + ", Square: " + (value * value));
}
// Generic List<int> avoids boxing/unboxing
Console.WriteLine("\nUsing Generic List (no boxing):");
System.Collections.Generic.List<int> genericList =
new System.Collections.Generic.List<int> {10, 20, 30};
foreach (int value in genericList) {
Console.WriteLine("Value: " + value + ", Square: " + (value * value));
}
}
}
The output of the above code is −
Values in ArrayList: Value: 10, Square: 100 Value: 20, Square: 400 Value: 30, Square: 900 Using Generic List (no boxing): Value: 10, Square: 100 Value: 20, Square: 400 Value: 30, Square: 900
Conclusion
Boxing and unboxing are automatic conversions between value types and object types in C#. Boxing is implicit and copies values from stack to heap, while unboxing is explicit and moves data from heap back to stack. Use generic collections like List<T> instead of non-generic collections to avoid the performance overhead of boxing and unboxing.
