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
What is boxing in C#?
Boxing in C# is the process of converting a value type to an object type. When boxing occurs, the value stored on the stack is copied to an object stored on the heap memory. This is an implicit conversion that allows value types to be treated as reference types.
Syntax
Boxing happens implicitly when a value type is assigned to an object variable −
int valueType = 50; object boxedValue = valueType; // implicit boxing
Unboxing requires explicit casting to convert back to the original value type −
object boxedValue = 50; int unboxedValue = (int)boxedValue; // explicit unboxing
How Boxing Works
Boxing is useful for storing value types in the garbage-collected heap. It creates a wrapper object around the value type, allowing it to be stored in collections that require reference types, such as ArrayList.
Example
using System;
public class Demo {
static void Main() {
int x = 50;
object ob = x; // boxing - implicit conversion
x = 100;
// The change in x won't affect the value of ob
Console.WriteLine("Value Type = {0}", x);
Console.WriteLine("Object Type = {0}", ob);
}
}
The output of the above code is −
Value Type = 100 Object Type = 50
Unboxing Example
Unboxing is the explicit conversion of an object type back to its original value type. The object's value stored on the heap is copied to the value type stored on the stack −
using System;
public class UnboxingDemo {
static void Main() {
int original = 25;
object boxed = original; // boxing
// Unboxing - explicit conversion required
int unboxed = (int)boxed;
Console.WriteLine("Original: {0}", original);
Console.WriteLine("Boxed: {0}", boxed);
Console.WriteLine("Unboxed: {0}", unboxed);
// Modifying unboxed doesn't affect boxed
unboxed = 75;
Console.WriteLine("After modification:");
Console.WriteLine("Boxed: {0}", boxed);
Console.WriteLine("Unboxed: {0}", unboxed);
}
}
The output of the above code is −
Original: 25 Boxed: 25 Unboxed: 25 After modification: Boxed: 25 Unboxed: 75
Boxing vs Unboxing Comparison
| Boxing | Unboxing |
|---|---|
| Converts value type to object type | Converts object type back to value type |
| Implicit conversion | Explicit conversion (requires casting) |
| Copies value from stack to heap | Copies value from heap to stack |
| Creates new object in heap memory | Extracts value from existing object |
Conclusion
Boxing in C# allows value types to be treated as reference types by creating a wrapper object on the heap. While boxing is implicit, unboxing requires explicit casting. Understanding boxing and unboxing is important for memory management and performance optimization in C# applications.
