September 2005 - Posts

Using intrinsic memory management with C#

Consider the following code snippet

// Declare the reader.
SqlDataReader reader = null;

// Use the reader here.
try
{
    // Create the reader.
    reader = new SqlDataReader(...);

    // Use the reader.
}
catch
{
}
finally
{
    // Check the reader for null. If it is not, then
    // dispose.
    if (reader != null)
    {
        // Dispose of it.
        ((IDisposable) reader).Dispose();
    }
}

Here, we are checking whether the reader is disposed or not. If not, we are disposing it explicitly. This is equivalent to being a good C# citizen and disposing off variables which are not required.

There is now a even better method of automatic memory management. The “using“ keyword.

Here is how it works.

SqlDataReader data;
using (data = command.ExecuteReader(CommandBehavior.CloseConnection))
{
     while( data.Read() )

     {
         Console.WriteLine("Company Name " +
           data.GetString(data.GetOrdinal("CompanyName"));

      }
}    // automatically calls data.Dispose();

 

Here is the link to the MSDN page describing this behavior (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csspec/html/vclrfcsharpspec_8_13.asp)

The beauty of this approach is that memory management becomes intrinsic. Hats off to the new keyword “using”.

Posted by Vipul Patel | with no comments
Filed under: , ,