Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memory allocation of value types and reference types in .net framework

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)

like image 771
MOZILLA Avatar asked Jul 15 '09 09:07

MOZILLA


People also ask

What are value data types and reference data types in C#?

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.

What is the difference between value types and reference types in .NET framework?

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.

Where is the memory allocated for reference types?

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.

How memory is allocated for value types?

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.


1 Answers

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.

like image 163
Jon Skeet Avatar answered Nov 23 '22 19:11

Jon Skeet