The using block calls the Dispose
method of the object used automatically, and the good point is that it is guaranteed to be called. So the object is disposed regardless of the fact an exception is thrown in the block of statements or not. It is compiled into:
{
StreamReader sr = new StreamReader(path);
try
{
while (sr.Peek() >= 0)
Console.WriteLine(sr.ReadLine());
}
finally
{
if(sr != null)
sr.Dispose();
}
}
The extra curly braces are put to limit the scope of sr
, so that it is not accessible from outside of the using block.