Why are structs stored on the stack while classes get stored on the heap(.NET)?

前端 未结 11 704
你的背包
你的背包 2020-12-01 03:05

I know that one of the differences between classes and structs is that struct instances get stored on stack and class instances(objects) are stored on the heap.

Sinc

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 03:34

    (edited to cover points in comments)

    To emphasise: there are differences and similarities between value-types and reference-types, but those differences have nothing to do with stack vs heap, and everything to do with copy-semantics vs reference-semantics. In particular, if we do:

    Foo first = new Foo { Bar = 123 };
    Foo second = first;
    

    Then are "first" and "second" talking about the same copy of Foo? or different copies? It just so happens that the stack is a convenient and efficient way of handling value-types as variables. But that is an implementation detail.

    (end edit)

    Re the whole "value types go on the stack" thing... - value types don't always go on the stack;

    • if they are fields on a class
    • if they are boxed
    • if they are "captured variables"
    • if they are in an iterator block

    then they go on the heap (the last two are actually just exotic examples of the first)

    i.e.

    class Foo {
        int i; // on the heap
    }
    
    static void Foo() {
        int i = 0; // on the heap due to capture
        // ...
        Action act = delegate {Console.WriteLine(i);};
    }
    
    static IEnumerable Foo() {
        int i = 0; // on the heap to do iterator block
        //
        yield return i;
    }
    

    Additionally, Eric Lippert (as already noted) has an excellent blog entry on this subject

提交回复
热议问题