Question

I am trying to write a custom rule (code analysis) where, if the body of a method contains empty statements, an error is raised.

However, there is one problem. I can not seem to figure out how to get the body of a method (the text that is in the method).

How can I get the text inside a method, and assign it to a string?

Thanks in advance.

For reference; I use c# in visual studio, with FxCop to make the rule.

Edit: Some code added for reference, this does NOT work.

using Microsoft.FxCop.Sdk;
using Microsoft.VisualStudio.CodeAnalysis.Extensibility;


public override ProblemCollection Check(Member member)
        {
            Method method = member as Method;
            if (method == null)
            {
                return null;
            }

            if (method.Name.Name.Contains("{}"))
            {
                var resolution = GetResolution(member.Name.Name);
                var problem = new Problem(resolution, method)
                                  {
                                      Certainty = 100,
                                      FixCategory = FixCategories.Breaking,
                                      MessageLevel = MessageLevel.Warning
                                  };
                Problems.Add(problem);
            }

            return Problems;
        }
Was it helpful?

Solution

FxCop doesn't analyse source code, it works on .Net assemblies built from any language.

You may be able to find whether the method contains a statement or not using FxCop, I advice you to read the documentation and check the implementation of existing rules to understand it.

An empty statement in the middle of other code might be removed by the compiler and you may not find it using FxCop. If you want to analyze source code you should take a look at StyleCop.

OTHER TIPS

However, there is one problem. I can not seem to figure out how to get the body of a method (the text that is in the method).

You can not. FxCop does not work based on the source, but analysis the compiled bytecode.

What you can do is find the source - which is not totally trivial - but you have to do so without the FxCop API. A start point may be analysing the pdb files (not sure where to find documentation) as they can point you to the file that contains the method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top