The using statement - CSharp Custom Type

CSharp examples for Custom Type:Exception

Introduction

The using statement provides an elegant syntax for calling 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();
  }
}

Related Tutorials