Rule Initialization

Custom rules inherit from BaseIntrospectionRule. Its constructor takes three arguments:

FxCop creates one instance of your rule class for each analysis thread. You may optionally override the BeforeAnalysis and AfterAnalysis methods. These methods are called once during the lifetime of each rule object (in other words, once per analysis thread).

[Warning]Warning

FxCop API objects are generally not thread-safe. Do not store them in globals declared using the static (C#) or Shared (VB.NET) keywords.

BaseIntrospectionRule has an overridable TargetVisibility property. If you want your rule to check only those elements that are exposed to third parties (for example, public methods in public classes) override this property to return TargetVisibilities.ExternallyVisible. If you do not override this property, FxCop uses TargetVisibilities.All by default. The following is a complete listing of all of the possible visibilities:

[Note]Note

It can be more efficient and convenient to override TargetVisibility on your rule instead of writing a lot of checks against TypeNode.IsVisibleOutsideAssembly properties.

Figure 7. Rule Boilerplate Code

using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.FxCop.Sdk;

namespace TutorialRules
{
  class MyCustomRule : BaseIntrospectionRule
  {
    public MyCustomRule() :
      base("MyCustomRule", "TutorialRules.TutorialRules",
      typeof(MyCustomRule).Assembly)
    {
    }

    public override TargetVisibilities TargetVisibility
    {
      get
      {
        return TargetVisibilities.All;
      }
    }

    public override void BeforeAnalysis()
    {
      // Do once-per-thread initialization.
    }

    public override void AfterAnalysis()
    {
      // Do once-per-thread cleanup. Rarely needed.
    }
  }
}