C# – using() and dispose with multiple wrapped streams

cdisposestream

Am I right that you'd only need a using() for the outermost stream if you're doing e.g

MemoryStream mstr = new MemoryStream();

using(StreamWriter w = new StreamWriter(mstr)) {
    ....
}

As disposing the StreamWriter should also dispose/close the underlying stream, there's no need to do this ?:

using(MemoryStream mstr = new MemoryStream())
using(StreamWriter w = new StreamWriter(mstr)) {
    ....
}

(Note these are just examples, for how to dispose wrapped streams, not looking for alternatives like just use a StringWriter etc.)

Best Answer

My rule of thumb: If it implements IDisposable, dispose of it.

While currently (and probably forever), calling StreamWriter.Dispose() closes the underlying stream, other stream-derived classes you may use in the future may not. Also, it seems not to actually call Dispose() either, so non-MemoryStreams may not get properly disposed (although I can't think of any that would suffer from that right now).

So, while you can safely dispose only of the StreamWriter, I find it a much better practice to always use using blocks for disposables whenever possible.

Related Topic