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)
All fundamental data types, Boolean, Date, structs, and enums are examples of value types. Examples of reference types include: strings, arrays, objects of classes, etc. To create reference types in C#, you can take advantage of these keywords: class, interface and delegate.
NET Framework are either treated by Value Type or by Reference Type. A Value Type holds the data within its own memory allocation and a Reference Type contains a pointer to another memory location that holds the real data.
Reference types are allocated on the heap. The heap is basically a block of memory used for that purpose. An object stored on the heap is primarily the fields of the object stored in the the memory allocated to the object.
The value type data will be allocated on the Stack and the reference type data will be allocated on the Heap. But when the same value types declared as array or used as data members of a class then they will be stored on a Heap. Also when the value types used in the struct then they will be stored on the Stack.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With