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
if (reader != null)
// Dispose of it.
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.
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 (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”.