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.

Comments (4)

  1. I think that this method will al not work. 😛

    if( method != null

     return null

    Shouldn’t this be changed to:

    if( method == null )

     return null ?

    Otherwise, you’ll get NullReferenceExceptions if the member is not a method, and if the member is a method, it will do nothing, except returning null.

  2. davkean says:

    Good spotting! Fixed.

  3. Chandran says:

    i am greating the New rools for our producted

  4. I want to fire on the naming of a local, however, whenever I pass the local to the Problem constructor,

Skip to main content