Finalizing Objects

Unlike many other programming languages (C, C++, Pascal, and so on), C# provides garbage collection. Your objects are destroyed after you are done with them—although not immediately after; they’re destroyed when the garbage collection process runs, which is determined by the system. You do not need to worry about cleaning up after your objects unless you use unmanaged or scarce resources. An unmanaged resource is an operating-system feature outside the .NET Framework, such as a connection to a database. A scarce resource is a resource that you have in limited quantity, perhaps because of licensing limitations or limited bandwidth. Graphics resources, such as fonts and brushes, are considered scarce because of the way the operating system works.

If you do control an unmanaged resource, you need to explicitly free that resource when you are done with it. Typically, you’ll manage this by implementing the IDisposable interface. (You will learn more about interfaces in Chapter 13.)

The IDisposable interface requires you to create a method named Dispose( ), which will be called by your clients.

If you provide a Dispose( ) method, you should stop the garbage collector from calling your object’s destructor. To stop the garbage collector, call the static method GC.SuppressFinalize( ), passing in the this reference for your object. Your finalizer can then call your Dispose( ) method. Thus, you might write:

using System; class Testing : IDisposable { bool is_disposed = false; ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.