Search code examples
c#streamdisposeword-wrap

Wrapping stream within a stream - will the wrapped stream be disposed properly?


I don't know how to check it, for example:

using (var stream = new StreamWriter(someStream))
{
    stream.Write("");
}

will this behave like this:

using (var stream1 = someStream)
{
    using (var stream2 = new StreamWriter(stream1))
         stream.Write("");
}

or if I'd wrap into GZipStream or any other stream... will the first example dispose every underlaying stream?

Update:

Finally it hit me - just implemented the Stream class myself:

class MyStream : Stream
{
    // fake stream implementation

    protected override void Dispose(bool disposing)
    {
        Console.WriteLine("disposing in my class");
        base.Dispose(disposing);
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyStream stream = new MyStream();
        DoSomething(stream);
        stream.Dispose();

        Console.WriteLine("end of program");
    }

    private static void DoSomething(Stream stream)
    {
        using (var writer = new StreamWriter(stream))
        {
            Console.WriteLine("inside using statement");
        }

        Console.WriteLine("after writing");
    }
}

and the result:

inside using statement
disposing in my class
after writing
disposing in my class
end of program

Solution

  • Calling close on the top most stream cascades down and will close them all, but this is not recommended because it's hard to keep tabs on whats open and not. As the other answerer said, use the using blocks religiously.

    Hope this helps!