Sobes.tech
Junior

What is boxing and unboxing in C#?

sobes.tech AI

Answer from AI

Boxing — is the conversion of a value type variable into an object reference (object type) or a reference type implemented by that value type (for example, interface). This happens implicitly.

Unboxing — is the explicit conversion of an object type back to a value type. It occurs through explicit casting.

// Boxing
int valueType = 123;
object objectType = valueType; // The value 123 is boxed into an object on the heap

// Unboxing
int newValueType = (int)objectType; // The value 123 is unboxed from the object on the heap back into a value type