CSharp - using resource statement

Introduction

Classes with resource handling usually implement System.IDisposable interface.

The interface defines a single parameterless method named Dispose to clean up these resources.

using statement can call Dispose on an IDisposable object within a finally block.

The following:

using (StreamReader reader = File.OpenText ("file.txt"))
{
       ...
}

is precisely equivalent to:

{
       StreamReader reader = File.OpenText ("file.txt");
       try
       {
         ...
       }
       finally
       {
          if (reader != null)
             ((IDisposable)reader).Dispose();
       }
}