This post discusses the aggressive and hungry nature of the garbage collection process in .NET as well as a concept that is often referred to as eager root collection.

I deliberately use the phrase garbage collection process and not garbage collector. This is because the behavior we are going to discuss in this post is actually the work of JIT and not the garbage collector. This statement is quite important as it goes against the popular notion about the role of garbage collector; however this JIT behavior does contribute to the garbage collection process by assisting the garbage collector as we will see in this post.

Consider the below code:

using System;
using System.Runtime.CompilerServices;

class Program
{
  static void Main(string[] args)
  {
      Tiger tiger = new Tiger();
      tiger.Run();
      var age = tiger.GetAge(2020);
      Console.WriteLine($"Tiger's age is {age}");
      Console.ReadLine();
  }
}

public class Tiger
{
    public int YearOfBirth { get { return 2010; } }

    ~Tiger()
    {
        Console.WriteLine("Tiger Dead");
    }

    public void Run()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        Console.WriteLine("Tiger is running");
    }

    public int GetAge(int currentYear)
    {
        return  currentYear - YearOfBirth;
    }
  }

#csharp #dotnet #garbage-collector #programming #tutorial #go

.NET Garbage Collection, Here We Go!
1.25 GEEK