Search code examples
c#clrboxingunboxing

Boxing and unboxing is a myth?


In C# Int type is derived from ValueType. ValueType is derived from Object type. Thus Int is an Object.

If every value type variable is already an Object, then what actually happens during boxing/unboxing?


Solution

  • There is a particular memory layout for Object instances. To save space and for compatibility with native code (COM, p/invoke, etc), instances of value types do not conform to that layout.

    "boxing" embeds the value inside an actual "object" instance with the expected layout. This enables polymorphic use by all the various functions that work on object instances and expect that interface.

    It's really not correct to say that Int32 is a subclass of Object. "boxed Int32" is, but "unboxed Int32" instances do not have any base class subobject at all. (Among other things, object layout includes a pointer to the actual most-derived type of the instance. The type of value-type objects is determined by their relationship to something else, they do not contain the type metadata. Or a monitor. Or all the other goodies of object. Boxed versions do.)