Within virtual memory, there are two very important areas of memory:
Stack memory This memory is used to store a variety of items, including local variables, return addresses, and base pointers in nonoptimized code. When it is created, each thread reserves 1MB of memory and commits 4KB of it for active use. As the thread is used, memory is committed in 4KB increments on an as-needed basis. Interestingly enough, with stack memory, the address space used goes down from a large address to a small address.
Heap memory This is another allocation of memory that can be use by reference-based variables, such as classes and arrays. Typically, a heap is used when the size of the allocation would be too large to place on the stack or the duration in use of the object may extend beyond the current local scope of the function. The really nice feature of C# is that the garbage collector (GC) does all the work of freeing used objects automatically that have a reference count of zero. This allows the developer to make allocations and to not need to worry about freeing the memory, as was required in C++.
The following example shows the use of heap and stack memory.
using System; namespace Client.Chapter_7___Memory_Management { class HeapandStackMemory { static void Main(string[] args) { //Creates a reference type MyClass ThisClass = new MyClass(); } } public class MyClass { public int MyInt; private long MyLong; public void DoSomething() { Console.WriteLine(MyInt); Console.WriteLine(MyLong); } } }