Search code examples
c#using

`using()` on a stream returned from a method


Assume I have a string class with a method ToStream().

class FooBar
{
    pubic Stream ToStream( )
    {
        byte[ ] barFooBytes = Encoding.UTF8.GetBytes( this.BarFoo );
        return new MemoryStream( barFooBytes );
    }
}

Now assume I have a class getting this stream.

class BarFoo
{
    pubic void DoCrazyStuff( )
    {
        using( Stream fooBarStream = ( new FooBar( ) ).ToStream( ) )
        {
            // Doing some really crazy stuff!
        }
    }
}

Does it still make sense to use a using outside of the method creating the stream?

Hint: This is not an actual real life scenario. It's a pure technical question of interest. So this code is minified just to clarify the question.


Solution

  • With using/IDisposable, the important question to be able to answer at any time is "who owns this object?". In this instance, the ToStream method has to return a Stream, so whilst it owned the object whilst it was running, it and the class it's part of assume no further responsibility for it. It therefore doesn't Dispose or wrap it in a using.

    Therefore, we can decide that ownership of the object has been passed back to the caller of the ToStream method. So, as the new owner of the object, it's your responsibility to wrap it in a using, manually Dispose of it or pass the ownership on to something else.


    As John's answer and the comments below it point out, a MemoryStream, specifically, doesn't significantly benefit from Dispose being called on it (the buffer remains allocated). However, it implements Dispose because it inherits from Stream and contractually, all that your ToStream method promised to provide was a Stream, not a MemoryStream, so using/Dispose is correct for the caller.