CSharp - Type Creation Finalizers

Introduction

Finalizers are class-only methods that execute before the garbage collector releases the memory for an unreferenced object.

The syntax for a finalizer is the name of the class prefixed with the ~

class Class1
{
       ~Class1()
       {
         ...
       }
}

Finalizers allow the following modifier:

Modifier Value
Unmanaged code modifier unsafe

Single-statement finalizers can be written with expression-bodied syntax:

~Class1() => Console.WriteLine ("Finalizing");