In my mind this is what I think of as boxing and unboxing. Nothing more. Can someone confirm that this is correct?
A box is a smart pointer to a heap allocated value of type T . When a box goes out of scope, its destructor is called, the inner object is destroyed, and the memory on the heap is freed. Boxed values can be dereferenced using the * operator; this removes one layer of indirection.
Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the common language runtime (CLR) boxes a value type, it wraps the value inside a System. Object instance and stores it on the managed heap. Unboxing extracts the value type from the object.
No.
While the general idea is right, it isn't quite correct. Boxed values are complete objects which conform to the memory layout for System.Object
. This means a v-table pointer (which provides the type-specific overloads for System.Object
virtual methods such as Equals
and GetHashCode
as well as serving as a type tag to prevent unboxing to an incompatible type), and an (optional) synchronization monitor.
The actual address stored in a handle to boxed value doesn't point to the content, but to the attached metadata.
Every value-type in .net actually defines two different kinds of things: a storage-location type, and a heap-object type. The heap type will, from an external point of view, behave much like a class
class Holder<T> where T:struct
{
public T This;
public override String ToString() { return This.ToString(); }
public override bool Equals(object other) { return This.Equals(other); }
etc.
}
which wraps exposes all of the value type's public methods. The heap type will have some additional magic, however, since it will implement any interfaces which the underlying value-type implements [as above, by wrapping calls to the value-type method]. Further, the Type
associated with a heap object will be the same as the Type
associated with a storage location.
Note that value-type storage locations hold instances of a value types and behave with value semantics, but a reference-type storage locations hold heap object references (or else null) and behave with mutable reference semantics (note that all value types, when boxed, behave as mutable reference types); the system does not terribly-conveniently provide for mutation, but boxed value-type instances can be mutated without the underlying value type having any say in the matter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With