Is a box value only a pointer to a copy of the value stored in the managed heap?

In my opinion, this is what I think about boxing and unboxing. Nothing more. Can someone confirm that this is correct?

enter image description here

+7
source share
2 answers

Not.

Although the general idea is correct, it is not entirely correct. Nested values โ€‹โ€‹are complete objects that correspond to the memory layout for System.Object . This means that the v-table pointer (which provides type-specific overloads for System.Object virtual methods such as Equals and GetHashCode , and also serves as a type tag to prevent unauthorized access to an incompatible type) and (optionally) a synchronization monitor.

The actual address stored in the descriptor in the box value does not indicate the content, but the attached metadata.

+6
source

Each value type in .net actually defines two different types of things: the type of storage location and the type of heap object. The type of heap will behave as a class from an external point of view

 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 public methods of type value. However, the heap type will have some additional magic, since it implements any interfaces that implements the base value type [as indicated above, by nulling calls to the type value method). In addition, the Type associated with the heap object will be the same as the Type associated with the storage location.

Note that value type storages store instances of value types and behave with semantics of values, but storage locations of a reference type contain references to heap objects (or else zero) and behave with mutable reference semantics (note that all types of values when pasted, behave like mutable reference types); the system is not terribly convenient for mutation, but instances of instances with short values โ€‹โ€‹can be mutated without a base value type if there are any words in this matter.

+1
source

All Articles