Example: Generic List<T> Instead of ArrayList

Generic collections provide many programming advantages and reduce bugs. In most cases, they should be used instead of their non-generic equivalents. This example checks for fields and local variables of type ArrayList and outputs warnings that they should be replaced with List<T>.

Rule XML:

<Rule TypeName="UseGenericList" Category="Tutorial" CheckId="TT1030">
  <Name>Use List&lt;T&gt; instead of ArrayList</Name>
  <Description>
    For greater type safety, use List&lt;T&gt; instead of ArrayList.
  </Description>
  <Url></Url>
  <Resolution>Replace ArrayList with List&lt;T&gt;.</Resolution>
  <MessageLevel Certainty="60">Warning</MessageLevel>
  <Email></Email>
  <FixCategories>DependsOnFix</FixCategories>
  <Owner></Owner>
</Rule>

Rule Implementation:

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

using Microsoft.FxCop.Sdk;

namespace TutorialRules
{
  class UseGenericList : BaseIntrospectionRule
  {
    private TypeNode m_ArrayList;

    public UseGenericList() :
      base("UseGenericList", "TutorialRules.TutorialRules",
      typeof(UseGenericList).Assembly)
    {
    }

    public override void BeforeAnalysis()
    {
      m_ArrayList = FrameworkAssemblies.Mscorlib.GetType(
        Identifier.For("System.Collections"), Identifier.For("ArrayList"));
    }

    public override ProblemCollection Check(Member member)
    {
      // Check field type, if this is a field.

      Field fld = member as Field;
      if (fld != null)
      {
        if (fld.Type == m_ArrayList)
        {
          this.Problems.Add(new Problem(this.GetResolution()));
        }
      }

      // Check local variable types, if this is a method.

      Method methd = member as Method;
      if (methd != null && methd.Locals != null)
      {
        foreach (Local lcl in methd.Locals)
        {
          if (lcl.Type == m_ArrayList)
          {
            this.Problems.Add(new Problem(this.GetResolution(), lcl.Name.Name));
          }
        }
      }

      return this.Problems;
    }
  }
}