When using Code Analysis and Code Contracts in combination, I get a lot of warnings like
CA1062: Microsoft.Design : In externally visible method 'Foo.Bar(Log)', validate parameter 'log' before using it.
In Foo.Bar, I have a contract that validates log
.
public Bar(Log log)
{
Contract.Requires(log != null);
log.Lines.Add(...);
// ...
}
Is there a way to make FxCop understand code contracts?
Code Contracts provide a language-agnostic way to express coding assumptions in . NET programs. The contracts take the form of preconditions, postconditions, and object invariants. Contracts act as checked documentation of your external and internal APIs.
Code analysis is the analysis of source code that is performed without actually executing programs. It involves the detection of vulnerabilities and functional errors in deployed or soon-to-be deployed software.
NET 4.0. Code Contracts API includes classes for static and runtime checks of code and allows you to define preconditions, postconditions, and invariants within a method.
No I do not think it's possible in the current build as the code generated by the contracts rewriter does not produce the standard pattern that FxCop is looking for.
Typically though I disable this particular FxCop rule when using code contracts. I find the static verifier more than makes up for the loss of this rule as it will yell about a lack of checking much more aggressively than FxCop. I would suggest the same approach here which will fix this problem for you.
Yes, as noted in my answer here, as of version 4.5.2 of the framework (possibly 4.5) it is possible to inform Code Analysis of the Code Contracts being enforced. An extension method and a marker attribute class must be defined like this:
public static class ContractExtensions {
/// <summary>Throws <c>ContractException{name}</c> if <c>value</c> is null.</summary>
/// <param name="value">Value to be tested.</param>
/// <param name="name">Name of the parameter being tested, for use in the exception thrown.</param>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "name")]
[ContractAbbreviator] // Requires Assemble Mode = Standard Contract Requires
public static void ContractedNotNull<T>([ValidatedNotNull]this T value, string name) where T : class {
Contract.Requires(value != null,name);
}
}
/// <summary>Decorator for an incoming parameter that is contractually enforced as NotNull.</summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class ValidatedNotNullAttribute : global::System.Attribute {}
Additional details are in my other answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With