colinfang
colinfang

Reputation: 21757

Does the boxed value type have the same address as the actual value type in the object?

From MSDN unbox does

  1. An object reference is pushed onto the stack.
  2. The object reference is popped from the stack and unboxed to a value type pointer.
  3. The value type pointer is pushed onto the stack.

Isn't the object reference identical to a value type pointer in this case? (both values are the address to the value type in the heap, since the value type is the only member in the object)?

For example, a one element array: the address of the array is the same as the address of the first element of the array.

void Main()
{
    int[] test = new []{1};
    unsafe
    {
        fixed (int* x = test)
        {
            fixed (int* y = &test[0])
            {
                Console.WriteLine((int)x);
                Console.WriteLine((int)y); // They are equal
            }
        }
    }
}

Upvotes: 0

Views: 283

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660279

Why does it need to unbox into a value type pointer?

Edit by 280Z28: The unbox instruction results in a pointer to the data to allow for a (potential) runtime performance advantage based on the following:

ECMA 335 Partition III §4.32 (excerpt):

Unlike box, which is required to make a copy of a value type for use in the object, unbox is not required to copy the value type from the object. Typically it simply computes the address of the value type that is already present inside of the boxed object.

The unbox.any instruction was added to CIL when generic types were added. Unlike unbox, this instruction places the value itself on the stack instead of a pointer to the value.

End 280Z28

Isn't the object reference identical to a value type pointer in this case?

No. The object reference refers to an object. The value type pointer points to a value.

Imagine you have a piece of paper with the number 12 on it. You put that piece of paper in a box, and you put the box in a warehouse. The position of the piece of paper is obviously related to the location of the box, but it is not identical to the location of the box. The managed reference is the location of the box. The value type pointer is the location of the piece of paper. The warehouse is the managed heap.

Maybe this will help. Think of a boxed int as an int[] with one element. The location of the array is different than the location of the first element of an array, right? Unboxing is essentially dereferencing the array.

Are both values are the address to the value type in the heap?

No. One value is a reference to an object. The other is a managed pointer to a value type.

Does line A or line B create a new copy (abstractly in IL, NOT machine code wise) of m?

I cannot for the life of me understand what you're trying to ask in this question.

Upvotes: 3

Related Questions