Garbage Collector
Learn about memory allocation and deallocation in .NET.
We'll cover the following...
Introduction
There’s a significant difference in how value and reference types are stored in memory. When we create a value-type variable, the value behind the variable is stored on the method stack. When the method returns (finishes running), the stack is cleared. Reference-type variables are also stored on the stack, but the variable contains the memory address of the region in the heap where the object is actually stored.
When a method finishes running, reference-type variables are also immediately deleted, but the objects these variables were pointing to aren’t cleared instantly. They’re deleted automatically some time later by the garbage collector.
Garbage collector
When there are no references pointing to an object, this object is considered an orphan. It’s the garbage collector’s job to clear memory areas that aren’t referenced by the application. The garbage collector doesn’t run every time a reference is deleted from the stack. The CLR launches the garbage collector only when necessary (for instance, when the app is running out of memory).
Objects in the heap aren’t stored in a sequential manner. There might be ...