Garbage collection
The Common Language Runtime (CLR) is responsible for managing the lifetime of objects and freeing memory when it's no longer used so that new objects can be allocated within the process. It does so through a component called the garbage collector (GC), which allocates objects on the managed heap in an efficient manner and clears memory by reclaiming objects that are no longer used. The garbage collector makes developing applications easier because you do not have to worry about manually freeing memory. This is what makes applications written for .NET to be known as managed.
Before we discuss how all this happens, you need to understand the difference between stack and heap, as well as the differences between types, objects, and references.
A type (whether introduced with the class
or struct
keyword in C#) is a blueprint for constructing objects. It is described in the source code using language features. An object is an instantiation of a type and lives...