Does Stream.Dispose always call Stream.Close (and Stream.Flush)

Solution 1:

Can I just call MySW.Dispose() and skip the Close even though it is provided?

Yes, that’s what it’s for.

Are there any Stream implementations that don't work as expected (Like CryptoStream)?

It is safe to assume that if an object implements IDisposable, it will dispose of itself properly.

If it doesn’t, then that would be a bug.

If not, then is the following just bad code:

No, that code is the recommended way of dealing with objects that implement IDisposable.

More excellent information is in the accepted answer to Close and Dispose - which to call?

Solution 2:

I used Reflector and found that System.IO.Stream.Dispose looks like this:

public void Dispose()
{
    this.Close();
}

Solution 3:

As Daniel Bruckner mentioned, Dispose and Close are effectively the same thing.

However Stream does NOT call Flush() when it is disposed/closed. FileStream (and I assume any other Stream with a caching mechanism) does call Flush() when disposed.

If you are extending Stream, or MemoryStream etc. you will need to implement a call to Flush() when disposed/closed if it is necessary.

Solution 4:

All standard Streams (FileStream, CryptoStream) will attempt to flush when closed/disposed. I think you can rely on this for any Microsoft stream implementations.

As a result, Close/Dispose can throw an exception if the flush fails.

In fact IIRC there was a bug in the .NET 1.0 implementation of FileStream in that it would fail to release the file handle if the flush throws an exception. This was fixed in .NET 1.1 by adding a try/finally block to the Dispose(boolean) method.

Solution 5:

Both StreamWriter.Dispose() and Stream.Dispose() release all resources held by the objects. Both of them close the underlying stream.

The source code of Stream.Dispose() (note that this is implementation details so don't rely on it):

public void Dispose()
{
    this.Close();
}

StreamWriter.Dispose() (same as with Stream.Dispose()):

protected override void Dispose(bool disposing)
{
    try
    {
        // Not relevant things
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            try
            {
                if (disposing)
                {
                    this.stream.Close();
                }
            }
            finally
            {
                // Not relevant things
            }
        }
    }
}

Still, I usually implicitly close streams/streamwriters before disposing them - I think it looks cleaner.