Junior — Middle
Explain the differences between packing and unpacking values in a programming language.
sobes.tech AI
Answer from AI
In C#, boxing is the process of converting a value type (e.g., int, bool) to an object of type System.Object or to an interface it implements. During boxing, the value is copied to the managed heap and wrapped in an object.
Unboxing is the reverse process, where an object containing a boxed value is converted back to a value type. During unboxing, a type check is performed, and the value is copied from the object to a variable of the value type.
Example:
int x = 123; // value type
object obj = x; // boxing
int y = (int)obj; // unboxing
Boxing and unboxing affect performance because they require memory allocation and data copying. Therefore, they should be minimized, especially in hot code paths.