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 books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.