Boxing and Unboxing in C#

What is Boxing and Unboxing?

Boxing and unboxing are processes in C# that convert value types to reference types and vice versa. Boxing occurs when a value type is implicitly converted to an object type, while unboxing extracts the value type from an object.

Boxing in C#

Boxing is the process of converting a value type (e.g., int, float) to a reference type (e.g., object). When a value type is boxed, the runtime wraps it inside a reference type, allowing the value type to be treated as an object.

Example of Boxing:

int num = 10;
object obj = num;  // Boxing: int to object
Console.WriteLine(obj);
        

In this example, the value of the integer num is boxed into the object obj. The obj now holds a reference to the value of num.

Unboxing in C#

Unboxing is the process of converting a reference type (e.g., object) back into a value type. When unboxing occurs, the runtime checks whether the object is compatible with the unboxed value type.

Example of Unboxing:

object obj = 10;  // Boxing: int to object
int num = (int)obj;  // Unboxing: object to int
Console.WriteLine(num);
        

In this example, the object obj is unboxed back into the integer num. The type of the object must match the value type during unboxing, or an exception will be thrown.

Different Types of Data Types

In C#, data types are broadly categorized into two types: Value types and Reference types.

Category Data Type Description
Value Types int Signed 32-bit integer
double 64-bit double-precision floating point
char Represents a Unicode character
bool Boolean value (true or false)
Reference Types object Base type of all types in C#
string Represents a sequence of characters

Key Points to Remember

  • Boxing converts a value type to a reference type.
  • Unboxing converts a reference type back to a value type.
  • Unboxing requires an explicit cast and must match the original value type.
  • Boxing and unboxing may involve performance overhead due to the memory allocation in heap and stack.