I want to fire on the naming of a local, however, whenever I pass the local to the Problem constructor, the source information for the method is always used. How do I get FxCop/Code Analysis to use the source information for the local instead?
Because the declaration of a local is not associated with an executable instruction, a local does not contain any source information within the pdb. However, any usages of the local (such as an assignment) does.
The following example shows when source information is provided and not provided:
As most locals are assigned at their time of declaration (such as in the case of value2 in the above example), a simple trick is use the source context of the first usage of the local in place of its declaration. This works in most situations.
The following example shows this (using the code from FAQ: How do I access the locals of a method in a custom rules?):
SourceContext sourceContext = FindSourceContext(local, method.Instructions);
Problem problem = new Problem(resolution, sourceContext); Problems.Add(problem); } } return Problems; }