21
votes

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?

3
I expect that you could write an FxCop addin to do the job. - GaTechThomas
Terje Sandstrom has a great blog entry that answers this: geekswithblogs.net/terje/archive/2010/10/14/… - Angerico Cariño
@Angerico Cariño I've updated the blogpost mentioned above with some new information regarding workarounds for this issue. - Terje Sandstrøm
@Dan: As of Framework V4.5.2 it is possible to inform CodeAnalysis of how to understand CodeContracts. see my answer at this post and at stackoverflow.com/questions/13273842/… - Pieter Geerkens

3 Answers

14
votes

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.

3
votes

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.

-2
votes

Specify the ArgumentNullException exception like this:

public Bar(Log log)
{
   Contract.Requires<ArgumentNullException>(log != null);
   log.Lines.Add(...);
   // ...
}

Fxcop expects to to throws the ArgumentNullException exception...