Can anybody tell me how to remove all CA2202 warnings from the following code?
public static byte[] Encrypt(string data, byte[] key, byte[] iv)
{
us
I just wanted to unwrap the code so we can see multiple calls to Dispose on the objects. The reality is that you are calling Dispose on objects twice:
memoryStream = new MemoryStream()
cryptograph = new DESCryptoServiceProvider()
cryptoStream = new CryptoStream()
streamWriter = new StreamWriter()
memoryStream.Dispose(); //implicitly owned by cryptoStream
cryptoStream.Dispose(); //implicitly owned by streamWriter
streamWriter.Dispose(); //through a using
cryptoStream.Dispose(); //INVALID: second dispose through using
cryptograph.Dispose(); //through a using
memorySTream.Dipose(); //INVALID: second dispose through a using
return memoryStream.ToArray(); //INVALID: accessing disposed memoryStream
While most .NET class are (hopefully) resilient against the mistake of multiple calls to .Dispose, not all classes are as defensive against programmer misuse.
Yes, the canonical documentation says that all class must be immune to programmer misuse from multiple calls to .Dispose:
The object must not throw an exception if its Dispose method is called multiple times
But this is the real world - where we're trying to eliminate bugs; not cause them. FX Cop knows this, and warns you.
You have a few choices;
Dispose once on any object; don't use using