Saturday 11 March 2017

Finalizer

A finalizer is a method that is inherited from the Object class, the base class of any reference type. what the finalizer does, is fire just before an object is collected by the garbage collector. if we take a look at our Person class

class Person {
    public string Name { get; set; }

    public Person(string Name) {
        Console.WriteLine($"Instantiate {Name}");
        this.Name = Name;
    }

    ~Person() {
        Console.WriteLine($"{Name}'s Finalizer fired");
    }

}

we see this bizarre ~Person() method or constructor; well it can be thought of as a destructor, this is our finalizer, whatever code we put in here will fire just before the object is garbage collected. Let's take a look at the main to test this

class Program
{
    static void Main(string[] args)
    {
        new Person("Pawel");
        Console.WriteLine("press key to garbage collect");
        Console.ReadKey();
        GC.Collect();
        Console.ReadKey();
    }

}

nothing magical about this, one interesting thing to note is that by instantiating a person class and not assigning it to a variable we're actually creating the object out in the heap without a reference on the stack making it a candidate for the garbage collector.

the finalizer is used to release unmanaged resources that are being used by this class. the base object class has no implementation so if you don't override it, it'll never fire. if you do overwrite it the garbage collector puts it into a finalization queue.

to read more about the msdn finalizer