Domanda

Turning the Code anlyisis on for a big project is showing a huge amount of CA1062 wanings, which are absolutely right IMO.

I would like to handle these automatically without having to go through each one,is there anyway to automate this in the entire code by using Assertion for all methods parameters or somehting like:

if (input == null)
{
    throw new ArgumentNullException("input");
}
È stato utile?

Soluzione

Yes, there are plenty of ways to automate addition of the null checks. Besides the AOP approach already mentioned by Bryan Ross, you could create a tool that modifies the source code based on the violations found in a code analysis report file. This would be more granular (i.e.: not impose null verifications where they might not actually belong), but you would need to invest a bit of effort in building the tool to do it.

That said, a large number of missing null checks is usually a pretty good indication that there are a variety of parameter validations missing from a code base. If you want to try to address all of these, manual effort would be required, and automating the null checks will potentially hide the areas on which you should be focusing.

Personally, I would tend to opt for a more manual clean-up, with VS snippets used to facilitate the more common validations (e.g.: not null, not empty, in range, enum in allowed list). The "TODO" suppression approach described at http://msmvps.com/blogs/calinoiu/archive/2007/04/22/fxcop-and-the-big-bad-backlog.aspx would potentially be useful if you want to enable the CA1062 rule before your cleanup effort ends (or even starts).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top