FAQ: How do I access the locals of a method in a custom rule? [Michael Fanning, David Kean]

Note: The custom rules API is likely to change in the next version of FxCop/Visual Studio.

Currently, the locals of a method are stored in a pseudo-instruction in the method's InstructionList. We plan to change this in a future version of the tool and the locals will directly hang off the method.

To access them, do the following:

public override ProblemCollection Check(Member member)
{
   Method method = member as Method;

   if (method == null)
      return null;

   if (method.Instructions.Length == 0)
      return null;

   LocalList locals = method.Instructions[0].Value as LocalList;

   if (locals == null)
      return null;

   for (int i = 0; i < locals.Length; i++)
{
      Local local = locals[i];

      // Do something
   }

   return base.Problems;
}

In FxCop 1.35, the LocalList is foreachable.