Use the “using” statement on objects that implement the IDisposable Interface

Posted by mbcrump on Geeks with Blogs See other posts from Geeks with Blogs or by mbcrump
Published on Mon, 03 May 2010 15:30:28 GMT Indexed on 2010/05/03 22:39 UTC
Read the original article Hit count: 181

Filed under:

From MSDN :

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In my quest to write better, more efficient code I ran across the “using” statement. Microsoft recommends that we specify when to release objects. In other words, if you use the “using” statement this tells .NET to release the object specified in the using block once it is no longer needed.

 

So Using this block:
  1. private static string ReadConfig()
  2.         {
  3.             const string path = @"C:\SomeApp.config.xml";
  4.  
  5.             using (StreamReader reader = File.OpenText(path))
  6.             {
  7.                 return reader.ReadToEnd();
  8.             }
  9.         }

 

The compiler converts this to:
  1. private static string ReadConfig1()
  2. {
  3.     StreamReader sr = new StreamReader(@"C:\SomeApp.config.xml");
  4.  
  5.     try
  6.     {
  7.         return sr.ReadToEnd();
  8.     }
  9.     finally
  10.     {
  11.         if (sr != null)
  12.             ((IDisposable)sr).Dispose();
  13.     }
  14.  
  15. }

© Geeks with Blogs or respective owner