Search code examples
c#idisposableusing

Any issue with nesting "using" statements in c#?


I recently downloaded Visual Studio 2013 and I ran the Code Analysis on a project I'm working on. Its thrown up a couple of issues that I'm working through but one in particular is about how I am using the "using" IDisposable statement.

Here's an example of my code:

using (MemoryStream msDecrypt = new MemoryStream(encryptedText.ToBase64Byte()))
{
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
    {
        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
        {
            return srDecrypt.ReadToEnd();
        }
    }
}

I understand the Analysis warning is trying to tell me that disposing of multiple objects in this way could throw an object disposed issue.

I'm sure that disposing on one object is not going to throw an exception in the case above. So should I modify my code or keep as is?


Solution

  • There should be no issue with your code as far as I can tell, I have always used nested using statements in the past.

    From looking through other questions I believe the problem is with the code analysis tool itself and both CA2000 and CA2202 rules. False positives often occur when using various stream and reader types with using statements.

    You should ignore the warnings and continue as alternative methods (such as try/finally) will produce bad code and your code is valid.