Reputation: 4968
I have a class like so...
public class Class1
{
public Class1()
{
byte[] plainText = new byte[1024];
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(plainText, 0, plainText.Length);
csEncrypt.FlushFinalBlock();
csEncrypt.Flush();
encrypted = msEncrypt.ToArray();
}
}
}
public ICryptoTransform encryptor { get; set; }
public byte[] encrypted { get; set; }
}
Code analysis throws the following warning. Do not dispose objects multiple times.
http://msdn.microsoft.com/en-us/library/ms182334.aspx.
I am not able to comprehend this line in the article above [Example section]... "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."
Upvotes: 2
Views: 1929
Reputation: 73472
It states that when you call Dispose
on a resource, it will dispose all the resource which it holds. So the inner resource here csEncrypt
which holds the outer resource msEncrypt
on csEncrypt.Dispose
it will have disposed msEncrypt
as well.
Later msEncrypt.Disopse
is called, so Code Analysis warns you about calling Dispose
multiple times.
Upvotes: 3