1

Suppose I want to validate some arguments for a constructor of an object to be used later. Also, suppose the criteria for validation of these arguments is elaborate.

For example, I want to check that some items I need to create an X509Certificate2 are legitimate. I've been calling the constructor inside a try{} and catching exceptions, but static analysis (correctly) reports "CA1804 remove unused locals A method declares a local variable but does not use the variable except possibly as the recipient of an assignment statement."

Consider this code:

string password = "bosco";
byte[] certyBytes = new byte[]{1,2,3};
try
{
  X509Certificate2 tpCert = new X509Certificate2(certBytes, password);
}
catch (CryptographicException)
{
  log.Debug("Bad cert.");
}

Static analysis reports CA1804 on line 5 above because of the unused tpCert.

Is there a better way to do this?

Eric
  • 4,201
  • 5
  • 27
  • 36
  • You should be able to `new` up the object without assigning it to anything. Alternatively, just suppress the warning in this case. :-) I treat analysis warnings as guidelines, not absolutes. Sometimes you know better than the tool. – Craig W. Feb 18 '15 at 16:48
  • Yeah, I tried it without assigning. That gives CA1806 "Do not ignore method results." I'm thiiiissss close to suppressing it. Just wanted to see if anybody had a better idea first. – Eric Feb 18 '15 at 17:08
  • 1
    :-) Then I'd go with the "ignore it" option for this particular case. IIRC there's an attribute you can throw on the method to tell it to ignore certain codes. – Craig W. Feb 18 '15 at 17:09
  • You could drop the new object into GC.KeepAlive but that is hardly better than suppressing the warning. – usr Feb 18 '15 at 17:43

1 Answers1

0

I usually avoid doing much work in the constructor (and especially things which can throw)

So my suggestion here is not to try suppressing the FXCop warning but instead use e.g. a static method which only checks the parameters.

If you cannot / do not want to change the X509Certificate2 class code, then I would do it like Craig W. suggested: just place a

[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals",
            Justification = "Testing parameters only")]

on it.

Rainer Schaack
  • 1,558
  • 13
  • 16