Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

boxing

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

like image 275
Foo Avatar asked May 23 '13 19:05

Foo


People also ask

How does Box work in Rust?

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.

What is boxing and unboxing used for?

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.


2 Answers

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.

like image 168
Ben Voigt Avatar answered Sep 27 '22 16:09

Ben Voigt


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.

like image 23
supercat Avatar answered Sep 27 '22 16:09

supercat