The using Statement

Step back for a moment and reflect on the preceding piece of code. We’re writing down how object disposal needs to be carried out in excruciating detail. But really, all we want to say is we’re using a certain resource and want to leave the guaranteed cleanup to the language and runtime. This is where the using statement comes in:

using (FileStream fs = File.OpenRead(path))using (StreamReader sr = new StreamReader(fs)){    string line;    while ((line = sr.ReadLine()) != null)    {        Console.WriteLine(line);    }}

This code does almost exactly the same as the original code. The using statement consists of two different parts. Between the parentheses is the resource-acquisition expression ...

Get C# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.