There’s a great pattern for ensuring that unmanaged resources are cleaned up in the .NET world. It’s called the Disposable pattern and it applies to any resource that implements the IDisposable interface. If you are writing an object that directly deals with unmanaged resources, such as files, database connections, network sockets, fonts, etc., then you are well advised to implement IDisposable and ensure your resources are cleaned up in your class’s Dispose() method. Having followed this pattern, you’ll allow client code to clean up after itself by calling Dispose() as soon as they are finished with the resources your class uses, rather than waiting for the garbage collector, which could take a long and indeterminate amount of time. Further, nice constructs like the using() statement make it relatively easy to deal with IDisposable objects in a clean fashion. You can even stack using() statements if you happen to be using multiple IDisposable objects together, which is not uncommon in data access code, like this:
using (SqlConnection myConnection = new SqlConnection(connectionString))
using (SqlCommand myCommand = new SqlCommand(query, myConnection))
{
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
while (myReader.Read())
{
Console.WriteLine(myReader[1]);
}
myReader.Close();
}
myConnection.Close();
}
Read more: Steve Smith
using (SqlConnection myConnection = new SqlConnection(connectionString))
using (SqlCommand myCommand = new SqlCommand(query, myConnection))
{
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection))
{
while (myReader.Read())
{
Console.WriteLine(myReader[1]);
}
myReader.Close();
}
myConnection.Close();
}
Read more: Steve Smith