The dreaded CA2202 warning in Visual Studio Code Analysis

319 views Asked by At

I'm going to create a new thread for this as previous accepted answers no longer work as of VS2012 and up. When using nested using statements, Visual Studio code analysis gives you the annoying CA2202 Do not dispose objects multiple times, for the following code:

using (MemoryStream msData = new MemoryStream(encodedData))
            {
                using (BinaryWriter wtr = new BinaryWriter(msData))
                {
                    wtr.Write(IV, 0, IV.Length);
                    wtr.Write(encrypted, 0, encrypted.Length);
                }
            }

This is annoying, because it is even listed in MSDN samples. Microsoft even has a recommended fix for this warning, however it no longer fixes the warning. This may or may not work for you, depending on what Visual Studio version/compiler you are using.

1

There are 1 answers

1
Michael Brown On

The above code can be fixed, properly, with the following change to the code:

MemoryStream msData = null;
try
{
    msData = new MemoryStream(encodedData);
    try
    {
        using (BinaryWriter wtr = new BinaryWriter(msData))
        {
            wtr.Write(IV, 0, IV.Length);
            wtr.Write(encrypted, 0, encrypted.Length);
        }
    }
    finally
    {
        msData = null;
    }
}
finally
{
    if (msData != null)
        msData.Dispose();
}

Aside from the code being much less readable, this is the solution. It would appear that recently they changed code analysis and as previously mentioned did not require the second inner try/finally block. I don't understand why, however. The previous fixes should have been enough to deal with disposing the MemoryStream object in the event of an exception.

I still think the CA2202 exception is bogus and the proper solution is to ignore the warning - underlying objects should not be disposing of references it does not own. This is merely here for discussion and reference.