TheChaseMan's Frenetic SoapBox

Always looking for better ways to do things...

Destructors and Finalizers in C#

The Design Guidelines for Finalization, Dispose, and Memory Management have been updated. .NET is a maturing platform and not only will design guidelines change, so will terminology. What we used to call destructors in C# are now being called finalizers, and the Dispose method is now being called a destructor.
 

class Foo : IDisposable

{

    //Destructor

    public void Dispose() {}

 

    //Finalizer

    ~Foo(){}

}

I also saw an example of stacking using statements, which I've not considered doing before. For example, notice using statement for the connection object stacked on top of the using statement for the command object...

using(SqlConnection connection = new SqlConnection(CONNECTIONSTRING))

using(SqlCommand command = new SqlCommand("SELECT CompanyName FROM Customers", connection))

{

    connection.Open();

    using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))

    {

        while(reader.Read())

        {

            Console.WriteLine(reader.GetString(0));

        }

    }

}


Digg!

posted on Sunday, April 10, 2005 11:35 AM

Feedback

No comments posted yet.