Garbage Collection
I want to explain the Garbage Collection concept in C#.
Purpose: The definition of Garbage Collection is it will clear the memory space, the type of memory we can call the expired objects that are no longer needed.
Advantages
- Automatic memory management.
- Release managed and unmanaged resources and resource cleanup.
- Reduce the errors.s
- Prevent the memory leaks.
- Optimize the performance.
I would like to explain the Generations approach:
- GEN 0: Generation 0 represents short-lived objects, which are temporary objects, such as those used in methods, LINQ queries, etc.
If objects survive in Gen 0, they are moved to Gen 1. This generation is also referred to as the youngest generation.
- GEN 1: Generation 1 acts as an intermediate stage between short-lived (Gen 0) and long-lived (Gen 2) objects.
Examples include objects passed between methods, temporary configuration data, or state information that is reused across multiple operations.
- GEN 2: Generation 2 represents the long-lived objects. These objects have survived garbage collection in both GEN-0 and GEN-1.
Examples include database connection strings, dependency injection containers, singleton objects, etc. This generation represents the oldest generation in the garbage collection hierarchy.
Using Finalization and Dispose
Finalizers (~ClassName()): Allow objects to clean up resources before being collected. However, finalizers delay GC, so it's better to use IDisposable for resource management.