Search code examples
c#disposeidisposableusingusing-statement

Multiple variables within same using block


I'm currently using two objects as follows:

using (var ms = new MemoryStream())
using (var bw = new BinaryWriter(ms))
{
    // work with ms and bw, both referenced here
}

It works "fine" and is in fact an answer here too. However, when I run VS2012's code analysis tool, I get a warning like:

CA2202  Do not dispose objects multiple times   
Object 'ms' can be disposed more than once in method '<my method name>'. 
To avoid generating a System.ObjectDisposedException you should not 
call Dispose more than one time on an object.

This leads me to believe there might an alternative way to handle this situation, but I don't know what it is.

Does anyone know what is the 'proper' way to use two objects within a single using block in a warning-free manner?


Solution

  • The BinaryWriter class is written such that it will dispose the underlying stream that you pass to it when you dispose the BinaryWriter unless you use the optional constructor parameter to tell it not to. Since the binary writer is disposing the underlying memory stream and you are also disposing of it in the using block it is being disposed of twice.

    Now, this isn't really an issue for most classes, as they should be (and memory stream is) written to work just fine if disposed twice, as long as you don't use it after it's dispose (you're not) so you can safely ignore the warning. If you want the warning to go away you can just take the memory stream out of the using since it's already being disposed.