Destroying Objects

Unlike many other programming languages (C, C++, Pascal, etc.), C# provides garbage collection. Your objects are automatically destroyed when you are done with them. You do not need to worry about cleaning up after your objects unless you use unmanaged resources. An unmanaged resource is an operating-system feature outside of the .NET Framework, such as a file handle or a database connection.

If you do control an unmanaged resource, you need to explicitly free that resource when you are done with it. Implicit control over this resource is provided with a destructor, which is called by the garbage collector when your object is destroyed. Note that this material is fairly advanced; it is included here for completeness.

You declare a C# destructor with a tilde as follows:

~MyClass(){}

It is not legal to call a destructor explicitly — your destructor will be called by the garbage collector. If you do handle precious unmanaged resources (such as file handles) that you want to close and dispose of as quickly as possible, you ought to implement the IDisposable interface. (You will learn more about interfaces in Chapter 14.)

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. ...

Get Learning C# 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.