Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
Rob McCabe Avatar asked Mar 11 '14 10:03

Rob McCabe


2 Answers

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.

like image 90
Matthew Hudson Avatar answered Oct 06 '22 01:10

Matthew Hudson


The reason From MSDN

Nested using statements (Using in Visual Basic) can cause violations of the CA2202 warning. If the IDisposable resource of the nested inner using statement contains the resource of the outer using statement, the Dispose method of the nested resource releases the contained resource. When this situation occurs, the Dispose method of the outer using statement attempts to dispose its resource for a second time.

in your case though. it is fine to use it like this. So, you should just suppress the warning.

OR

you can just go the ugly way of suppressing the warning by modifying your code by implementing Try/finally. Although, you should really avoid that.

like image 22
Ehsan Avatar answered Oct 06 '22 01:10

Ehsan