Search code examples
c#filestreamdisposestreamreaderusing

C# - nested using statements redundant?


I came across the following example code in the MSDN documentation, demonstrating the use of the System.IO.StreamReader class to read UTF-8 text from a System.IO.FileStream object. The two nested using statements struck me as redundant - surely calling Dispose() on one of the objects does the trick, and properly releases the file handle? (Source: http://msdn.microsoft.com/en-us/library/yhfzs7at.aspx)

using (FileStream fs = new FileStream(path, FileMode.Open)) 
{
    using (StreamReader sr = new StreamReader(fs)) 
    {

        while (sr.Peek() >= 0) 
        {
            Console.WriteLine(sr.ReadLine());
        }
    }
}

Would it not be simpler, and equally correct, to rewrite that code in the following way?

using (FileStream fs = new FileStream(path, FileMode.Open)) 
{
    StreamReader sr = new StreamReader(fs);

    while (sr.Peek() >= 0) 
    {
        Console.WriteLine(sr.ReadLine());
    }
}

Solution

  • According to the documentation, The StreamReader object calls Dispose() on the provided Stream object when StreamReader.Dispose is called. This means using the StreamReader guarantees disposal of the underlying Stream. It does not hold vice versa: disposing only the Stream does not suffice - the StreamReader may be allocating other native resources. So the second sample is not correct.

    (using only the StreamReader does not cover the case that the StreamReader constructor can throw. To cover this case, both using's would be needed. Since it only throws for non-readable or null streams, this may not be relevant though.)

    In general, you should always dispose on every disposable object. It is part of the IDisposable contract that it does not hurt to dispose an object multiple times, and the overhead of doing so is low.