Use the “using” statement on objects that implement the IDisposable Interface
- by mbcrump
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: private static string ReadConfig() { const string path = @"C:\SomeApp.config.xml"; using (StreamReader reader = File.OpenText(path)) { return reader.ReadToEnd(); } } The compiler converts this to: private static string ReadConfig1() { StreamReader sr = new StreamReader(@"C:\SomeApp.config.xml"); try { return sr.ReadToEnd(); } finally { if (sr != null) ((IDisposable)sr).Dispose(); } }