Search code examples
c#memorymemory-managementheap-memorystack-memory

Stack and heap in c sharp


Possible Duplicate:
Why are structs stored on the stack while classes get stored on the heap(.NET)?

Can anyone tell me that how the allocation of memory is done that which object is to be stored in stack and which to be in heap portion of the memory?


Solution

  • 3 rules of thumb:

    1. Objects are stored on the heap. These include instances of reference-types and boxed value-types.
    2. Local variables and parameters are stored on the stack. For local value-types, this means that the value itself is stored on the stack. For local reference-types, only the reference will be on the stack (Edit: Exceptions noted by Eric Lippert - value-type locals closed over outer variables, iterator-block value-types).
    3. Fields are stored where the containing instance is located. For example, a value-type field of a class will be stored on the heap. The reference-part of a reference-type field of a struct declared as a local stored on the stack will also be on the stack.