memory allocation of value types and reference types in .net framework

Is there an advanced article which I can read that can explain how memory is allocated for different types (value and reference) in .net framework.

for example we know that value types are allocated space on a stack, but how is that managed?

Also how are reference types managed in a heap and where are the actual values stored. (Reference type like any Class will contain many value types, where are they saved and how are they managed)


It's more complicated than you might think. Even your claim that "value types are allocated on the stack" isn't correct. For example:

class Foo
{
    int x;
}

int is a value type, but the value for x will always be on the heap because it will be stored with the rest of the data for the instance of Foo which is a class.

Additionally, captured variables for anonymous functions and iterator blocks make life trickier.

I have an article about C# heap/stack memory you may find useful, but you might also want to read Eric Lippert's blog post on "The stack is an implementation detail". In particular, a future C# compiler could decide to store all of its local variables on the heap, using the stack just to hold a reference to an instance created at the start of the method... that wouldn't defy the C# spec at all.


A value type is "allocated" where it is defined.

What that means depends on where you define it:

  • In a class/struct, as a field in that struct, enlarging the class/struct in memory to fit the value type value in there
  • As a local variable in a method, on the stack, or as a register, or as a field in a generated class (when using "closures"), depending on optimizations
  • As a parameter to a method, on the stack or as a register, depending on optimizations
  • A reference type is sort of a dual value. A reference type is at heart a pointer, and the pointer value follows the same rules for "allocation" as a value type, but once you store a value in it, ie. a reference to an object, that object is on the heap somewhere else.

    In other words, the reference variable itself is "allocated" as a value type, but the object it refers to is on the heap.

    When you construct an object from a class, space is allocated on the heap to fit all the fields of that class + some overhead in that space.

    I seem to recall Jon Skeet having an article about the subject, I'm sure he'll jump in with an answer really soon so stay tuned.


    This article seems advanced without going overboard. It should provide you with a much better understanding:

    http://www.simple-talk.com/dotnet/.net-framework/understanding-garbage-collection-in-.net/

    链接地址: http://www.djcxy.com/p/80216.html

    上一篇: 在类中声明的变量的内存分配

    下一篇: .net框架中值类型和引用类型的内存分配