Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

c# - memory allocation for value type inside reference type in .net

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 types. Considering the reference types in the class will get instantiated sometime during the execution, how the memory is allocated for each member of such a class? How the pointer is stored and accessed for each of these members? Also which type is created in which memory structure, i.e. stack or heap?

I know this much that if only a variable of value type is used in my code then its value and all the other details like its type, etc are stored in the stack. Similarly if a reference type is instantiated then the actual object is created in the heap and a pointer to this memory location is stored in the stack. But what about value types present inside a class (reference type)? Where are they stored and how are they accessed?

I have given an example of such a class below. An answer in reference to this class will be very helpful.

public class Employee
{
    public int EmpNo { get; set; }
    public string EmpName { get; set; }
    public BankAccDetails AccDetails { get; set; }
}

public class BankAccDetails
{
    //Other properties here
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...