memory allocation for value type inside reference type in .net

前端 未结 2 447
盖世英雄少女心
盖世英雄少女心 2020-12-15 12:30

I think this is a very trivial question but I am not able to get a definite answer to it on the net.

I have a class which contains both value types and reference typ

相关标签:
2条回答
  • 2020-12-15 12:59

    But what about value types present inside a class (reference type)? Where are they stored and how are they accessed?

    Value types are stored where they are declared. In your case, they will be on heap.

    But you should see the following articles with respect to memory management in C#.

    The Truth about value types - Eric Lippert

    in the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value.

    The Stack Is An Implementation Detail, Part One - Eric Lippert
    Memory in .NET - what goes where - Jon Skeet

    0 讨论(0)
  • 2020-12-15 13:06

    They are initialized to their default values, which is 0 for int and float, false for bool, and null for every other data type. Structs are initialized using the default constructor. See also the default keyword to initialize generic types without knowing whether they are simple data types or not.

    The object is stored on the heap, with each field having a bit of space, either the value for a value type, or the pointer for other types. They are aligned, which means there might be gaps of space in the object.

    0 讨论(0)
提交回复
热议问题