Is a boxed value just a pointer to a copy of the value stored in the managed heap?

StackOverflow https://stackoverflow.com/questions/16722433

  •  30-05-2022
  •  | 
  •  

Question

In my mind this is what I think of as boxing and unboxing. Nothing more. Can someone confirm that this is correct?

enter image description here

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top