Search code examples
c#visual-studiofxcop

Get method body c#


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;
        }

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.