.NET Framework Garbage Collection A basic example of (garbage) collection

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Given the following class:

public class FinalizableObject 
{
    public FinalizableObject()
    {
        Console.WriteLine("Instance initialized");
    }

    ~FinalizableObject()
    {
        Console.WriteLine("Instance finalized");
    }
}

A program that creates an instance, even without using it:

new FinalizableObject(); // Object instantiated, ready to be used

Produces the following output:

<namespace>.FinalizableObject initialized

If nothing else happens, the object is not finalized until the program ends (which frees all objects on the managed heap, finalizing these in the process).

It is possible to force the Garbage Collector to run at a given point, as follows:

new FinalizableObject(); // Object instantiated, ready to be used
GC.Collect();

Which produces the following result:

<namespace>.FinalizableObject initialized
<namespace>.FinalizableObject finalized

This time, as soon as the Garbage Collector was invoked, the unused (aka "dead") object was finalized and freed from the managed heap.



Got any .NET Framework Question?