CA2202, how to solve this case

You should suppress the warnings in this case. Code that deals with disposables should be consistent, and you shouldn’t have to care that other classes take ownership of the disposables you created and also call Dispose on them.

[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static byte[] Encrypt(string data, byte[] key, byte[] iv) {
  using (var memoryStream = new MemoryStream()) {
    using (var cryptograph = new DESCryptoServiceProvider())
    using (var cryptoStream = new CryptoStream(memoryStream, cryptograph.CreateEncryptor(key, iv), CryptoStreamMode.Write))
    using (var streamWriter = new StreamWriter(cryptoStream)) {
      streamWriter.Write(data);
    }
    return memoryStream.ToArray();
  }
}

UPDATE: In the IDisposable.Dispose documentation you can read this:

If an object’s Dispose method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if its Dispose method is called multiple times.

It can be argued that this rule exists so that developers can employ the using statement sanely in a cascade of disposables, like I’ve shown above (or maybe this is just a nice side-effect). By the same token, then, CA2202 serves no useful purpose, and it should be suppressed project-wise. The real culprit would be a faulty implementation of Dispose, and CA1065 should take care of that (if it’s under your responsibility).

Leave a Comment