O'Reilly logo

C# 5.0 Unleashed by Bart De Smet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required