Example: Class Field Name Prefixes

It is a common practice to use the prefix "m_" (member) for instance fields and "g_" for static fields in classes.

The implementation is straightforward; a few special cases are recognized for compatibility with the Windows Forms designer and Visual Basic.

Rule XML:

<Rule TypeName="ClassFieldNamePrefixes" Category="Tutorial" CheckId="TT1010">
  <Name>Class field names should use the 'm_' and 'g_' suffixes.</Name>
  <Description>
    Instance fields in classes should begin with the 'm_' prefix.
    Static fields in classes should begin with the 'g_' prefix.
  </Description>
  <Url></Url>
  <Resolution Name="Static">Prefix the static field '{0}' with 'm_'.</Resolution>
  <Resolution Name="Instance">Prefix the instance field '{0}' with 'g_'.</Resolution>
  <MessageLevel Certainty="95">Warning</MessageLevel>
  <Email></Email>
  <FixCategories>Breaking</FixCategories>
  <Owner></Owner>
</Rule>

Rule Implementation:

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

using Microsoft.FxCop.Sdk;

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

    public override ProblemCollection Check(Member member)
    {
      if (!(member.DeclaringType is ClassNode))
        return this.Problems;

      Field fld = member as Field;
      if (fld == null)
        return this.Problems;

      if (fld.IsStatic && !fld.Name.Name.StartsWith("g_", StringComparison.Ordinal) &&
        fld.Name.Name != "__ENCList")
      {
        this.Problems.Add(new Problem(this.GetNamedResolution("Static", fld.Name.Name)));
      }
      else if (!fld.Name.Name.StartsWith("m_", StringComparison.Ordinal) &&
        fld.Name.Name != "__ENCList" && fld.Name.Name != "components")
      {
        this.Problems.Add(new Problem(this.GetNamedResolution("Instance", fld.Name.Name)));
      }

      return this.Problems;
    }
  }
}