bkr
bkr

Reputation: 1484

CA2202 Do not dispose of objects multiple times - which is the preferred object to dispose?

I get the CA2202 warning on the following piece of code

using (MemoryStream msDecrypt = new MemoryStream(encrypted))
        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
        return srDecrypt.ReadToEnd();

This code is triggering on both msDecrypt and csDecrypt having their own using statements. Is there a preferred object to dispose of? The outer (msDecrypt) or the inner (csDecrypt)- and if so why?

This question is not a duplicate of this thread because I want to know generally speaking - which is better to dispose of - the inner/later object or the outer/earlier object and why?

Upvotes: 2

Views: 229

Answers (1)

John Hodge
John Hodge

Reputation: 1715

This is explained here if you scroll down to the Example section. In short, this is caused by the resource in the inner using block also containing the resource of the outer using block. When you call Dispose on the inner resource, it also disposes of the outer resource that is contained therein.

The suggested fix is to wrap the whole thing in a try block, put the inner resource in a using block, and then call Dispose on the outer resource inside of a finally block if it is not already null.

To answer your question more directly, the inner resource should be the one that is preferable to dispose of.

Upvotes: 2

Related Questions