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;
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?