C# Interview Question #7

What is boxing and unboxing in C#?

C# & .NET Fundamentals Junior Beginner

Quick Interview Answer

Boxing is the conversion of a value type to object or to an interface type implemented by that value type. It involves creating an object representation of the value.

Detailed Explanation

Boxing is the conversion of a value type to object or to an interface type implemented by that value type. It involves creating an object representation of the value.

Unboxing extracts the value type from a boxed object and requires an explicit cast.

Boxing and unboxing can have performance costs because boxing normally requires allocation and copying. Generic collections such as List<int> help avoid unnecessary boxing compared with older non-generic collections.

Code Example

int number = 10;
object obj = number;       // Boxing
int result = (int)obj;     // Unboxing