Using intrinsic memory management with C#

Consider the following code snippet

// Declare the reader.
SqlDataReader reader = null;

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

    // Use the reader.
    // 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 ” +

}    // automatically calls data.Dispose();


Here is the link to the MSDN page describing this behavior (

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