Section 7.7. Destroying Objects


7.7. Destroying Objects

Unlike many other programming languages (C, C++, Pascal, etc.), C# provides garbage collection . Your objects are destroyed after you are done with them. 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 of the .NET Framework; a scarce resource is a resource that you have in limited quantity, perhaps because of licensing limitations (such as database connections).

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.

This material is fairly advanced and is included here for completeness. Feel free to skip this section and come back if and when you need it. It's your book; you paid for it. (You did, right?)


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

 ~MyClass( ){} 

This syntax is actually translated by the compiler into:

 protected override void Finalize()     {        try        {            // do work here        }        finally        {             base.Finalize();        }     } 

For this reason, some programmers refer to the destructor as a finalizer .

It is not legal to call a destructor explicitlyyour destructor (finalizer) 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 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 destructor can then call your Dispose( ) method. Thus, you might write:

 using System;     class Testing : IDisposable     {        bool is_disposed = false;        protected virtual void Dispose( bool disposing )        {           if ( !is_disposed ) // only dispose once!           {              if ( disposing )              {                 Console.WriteLine( "Not in destructor,                 OK to reference other objects" );              }              // perform cleanup for this object              Console.WriteLine( "Disposing..." );           }           this.is_disposed = true;        }        public void Dispose( )        {           Dispose( true );           // tell the GC not to finalize           GC.SuppressFinalize( this );        }        ~Testing( )        {           Dispose( false );           Console.WriteLine( "In destructor." );        }     } 

For some objects, you'd rather have your clients call the Close( ) method. (For example, Close( ) makes more sense than Dispose( ) for file objects.) You can implement this by creating a private Dispose( ) method and a public Close( ) method and having your Close( ) method invoke Dispose( ) .

Because you cannot be certain that your user will call Dispose( ) reliably, and because finalization is nondeterministic (that is, you can't control when the garbage collector will run), C# provides a using statement to ensure that Dispose( ) is called at the earliest possible time. The idiom is to declare which objects you are using and then to create a scope for these objects with curly braces. When the close brace is reached, the Dispose( ) method will be called on the object automatically, as illustrated here:

 using System.Drawing;     class Tester     {      public static void Main( )      {          using (Font theFont = new Font("Arial", 10.0f))          {          // use the font          }      }     } 

Because Windows only lets you have a small number of Font objects, we want to dispose of it at the earliest opportunity. In this code snippet, the Font object is created within the using statement. When the using statement ends, Dispose( ) is guaranteed to be called on the Font object.



Learning C# 2005
Learning C# 2005: Get Started with C# 2.0 and .NET Programming (2nd Edition)
ISBN: 0596102097
EAN: 2147483647
Year: 2004
Pages: 250

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net