Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation for value type inside reference type in .net

Tags:

c#

.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
}
like image 717
samar Avatar asked Aug 09 '12 03:08

samar


1 Answers

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

like image 172
Habib Avatar answered Sep 28 '22 22:09

Habib