Question: Explain Garbage Collection in .Net
What is .NET garbage collection?
Advantage:
What is .NET garbage collection?
The garbage collection (GC) is new feature in Microsoft . net framework. When we have a class that represents an object in the runtime that allocates a memory space in the heap memory. All the behavior of that objects can be done in the allotted memory in the heap.
- The .Net framework provides a new mechanism for releasing unreferenced objects from the memory this process is called garbage collection(GC).
- When program creates an object the object takes up the memory.
- Later when the program has no more references to that object the objects memory becomes unreachable but it is not immediately freed.
- The garbage collection checks to see if there are any objects in the heap that are no longer being used by the application.
- If such objects exist then the memory used by these objects can be reclaimed.
- So these unreferenced objects should be removed from memory, Then the other new objects you create can find a place in the heap.
- The releasing of unreferenced objects is happening automatically in .Net languages by the garbage collector(GC).
- In .Net languages there is a facility that we can call garbage collector(GC) explicitly in the program by calling System.GC.Collect.
- Allow us to develop an application without having worry to free memory.
- Allocates memory for objects efficiently on the managed heap.
- Reclaimes the memory for no longer used objects and keeps the free memory for future allocation.
- provides memory safety by making sure that an object cannot use the content of another object.