Garbage collector [ GC ] is responsible for the "automatic memory management - AMM" in .NET framework. Garbage collector [ GC ] is one of the properties of .NET framework components CLR [ common language runtime ].
Why there is a need of "Memory management"?
Ans : Basically, Operating Sytem [ OS ] stores the data that is processed and accessed during programming / development of the applications in the memory. Sometimes that memory gets filled and developers may not be able to store the new data / input that is coming into.
At this moment, developers need to write a seperate logic for the management of the memory, where they've to identify the unused or unnecessary data that has occupied the OS memory and need to write the logic for releasing that memory which is a burden for the developers.
Hence, to avoid the burden on the developers , this "automatic memory management" is needed.
In .NET, Garbage collector [ GC ] is responsible for the "automatic memory management" and it's popular for it's efficiency.
Working of Garbage collector [ GC ] :
Garbage collector [ GC ] identifies the active and idled objects from the heap memory , retains the active objects and destroys the idled objects and releases the memory.
NOTE: GC provides automatic memory management only for "Reference types"
Generations of GC :
Garbage collector [ GC ] divides the heap memory into 3 parts or generations and are named as Generation 0 , Generation 1 & Generation 2. Always Gen 0 > Gen 1 > Gen 2
Whenever a new object gets created , it occupies the memory only in Gen 0.
When Gen 0 gets filled completely, Garbage collector [ GC ] performs an action called "Collection" on Gen 0 , identifies the active and idled objects , pushes the active objects into Gen 1 and destroys the idled objects from the Gen 0 and releases the memory.
When Gen 1 gets filled completely, Garbage collector [ GC ] performs an action called "Collection" on Gen 1 , identifies the active and idled objects , pushes the active objects into Gen 2 and destroys the idled objects from the Gen 1 and releases the memory.
When Gen 2 gets filled completely, Garbage collector [ GC ] performs an action called "Collection" on Gen 2 , identifies the active and idled objects , retains the active objects and destroys the idled objects from the Gen 2 and releases the memory.
Thus , Garbage collector [ GC ] is efficient and responsible for "Automatic memory management" in .NET framework.