What is garbage collection in C#

Garbage collection in C# is an automatic memory management feature that helps to reclaim memory used by objects that are no longer referenced in the application. This process prevents memory leaks and optimizes memory usage, making it easier for developers to manage resources without manually releasing memory.

The garbage collector (GC) in .NET runs on a separate thread and can determine when objects are unreachable, meaning they are no longer accessible in the code. When this occurs, the GC will free up that memory, making it available for new objects.

// Example of Garbage Collection in C# class Program { static void Main(string[] args) { // Creating an object Person person = new Person("John Doe"); // The person object is now in use Console.WriteLine(person.Name); // Removing reference to the object person = null; // Suggesting garbage collection GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Garbage collection has been called."); } } class Person { public string Name { get; set; } public Person(string name) { Name = name; } }

Garbage collection C# memory management .NET automatic memory reclamation