If you are working with objects instantiated from classes that implement the IDisposable interface, you should take care to call the Dispose method on the object. If Dispose is not called, then automatic disposal eventually occurs as a consequence of garbage collection. This has obvious implications, especially if the object makes use of unmanaged resources (file handles, database connections, etc). We know that eventually GC will clean things up, but since we don’t know when, we might run out of connections or file handles in the meantime.

One common practice is to put Dispose calls into a finally block. For example:

try 
{ 
    conn = new SqlConnection(connectionString); 
    comm = new SqlCommand(commandString, conn); 
conn.Open(); comm.ExecuteNonQuery(); } finally { if (null != comm); comm.Dispose(); if (null != conn) conn.Dispose(); }

The downside here is that this practice requires that the developer be aware of which resources implement IDisposable and then requires that they consistently apply the finally block. It also produces slightly more cumbersome code.

Another option is to use the using keyword, which translates into a cleaner statement while implicitly generating the same result under the covers. Pit differently, usage of the resource is implicitly enclosed in a try statement that includes a finally clause, which, as we saw above, disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.

The example below creates a file named sample.txt and writes a line of text to the file. 

using System; 
using System.IO; class UsingTest { static void Main() { using (TextWriter textWriter = File.CreateText("sample.txt")) { textWriter.WriteLine("Some text here"); } } }

Because the TextWriter and class implement the IDisposable interface, the example can use using statements to ensure that the underlying file is properly closed following the write operation.

Under the covers, this using statement would take an expanded form of

{ 
   TextWriter textWriter = File.CreateText("sample.txt");
   try
   {
      textWriter.WriteLine("Some text here");
   }
   finally
   {
      if (textWriter != null)
         ((IDisposable)textWriter).Dispose();
   }
}