.NET Framework A basic example of (garbage) collection


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.