How Finalizers Are Implemented

To justify our naming of finalizers over destructors, take a look in ILDASM at the generated code, as shown in Figure 12.6. As you can see, C# destructors get turned into methods that override the Finalize method, which is defined on System.Object. The user’s custom logic and a call to the base class’s finalizer live inside this method. Although we still have to learn about inheritance, the idea is simple. When a class derives from another one to specialize its behavior, it’s essential for the base class’s cleanup logic to run as part of finalization. The code in our finalizer will be equivalent to the following:

~A(){    try {        Console.WriteLine("Finalized instance " + _id); ...

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.