How much memory required when Value Type is Boxed into Reference Type in C#?

.net, c#

Solution

First to help explain the "why", from the C# 5 Specification: Section 4.3.1 Boxing conversions

The actual process of boxing a value of a non-nullable-value-type is best explained by imagining the existence of a generic boxing class, which behaves as if it were declared as follows:

sealed class Box<T>: System.ValueType
{
  T value;
  public Box(T t) {
      value = t;
  }
}

Boxing of a value v of type T now consists of executing the expression new Box(v), and returning the resulting instance as a value of type object. Thus, the statements

int i = 123;
object box = i;

conceptually correspond to

int i = 123;
object box = new Box<int>(i);

To answer if it is stored on the stack or the heap, the answer is both. See Boxing and Unboxing on the MSDN.

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o. 
object o = i;

The result of this statement is creating an object reference o, on the stack, that references a value of the type int, on the heap. This value is a copy of the value-type value assigned to the variable i. The difference between the two variables, i and o, is illustrated in the following figure.

So on the stack there are `sizeof(Object)` bytes stored, and on the heap there are `sizeof(int)` + Class overhead stored.

I could not find any good documentation on how large that overhead is, it is most likely 8 to 16 bytes in size.

Problem

``` public class A { public static void Main(string[] args) { int num = 13; // It stores in Stack and takes 4 bytes object obj = 13; // Where it is Stored (Stack or Heap)? //How much size obj require? } } ``` I just want to know the extra bits required for obj and why ?

Original source