Defining Finalizers in C#

Before discussing their behavior in full detail, also contrasting it to the C++ behavior shown earlier, we first show how to declare a finalizer in C#. Because they share the C++ syntax, the language specification calls them destructors, but to avoid confusion with any of your C++ programmer friends, let’s call them finalizers.

Here’s a finalizer defined in C#, using the class’s name prefixed with a ~ character:

class A{    ~A()    {        Console.WriteLine("Destructing instance of A");    }}

Finalizers cannot have an access modifier, nor can they have any parameters. They cannot be called explicitly by the user (so it doesn’t make sense to pass parameters), as you will see.

Get C# 5.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.