Search code examples
c#roslynroslyn-code-analysismicrosoft.codeanalysis

SyntaxWalker Visitor doesn't visit Methods


I got this walker

internal class MyWalker : CSharpSyntaxWalker
{
            public int MethodCount { get; private set; }

    public MyWalker() : base(Microsoft.CodeAnalysis.SyntaxWalkerDepth.Trivia)
    { }

    public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
    {
         MyMethodCount ++;
    }

    public override void VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        Class++;
        Complexity++;
    }
}

I call the walker with this code

    var code = @"
    public class foo
    {
        public void MyMethod()
        {

        }
    }
";

  SyntaxTree node = CSharpSyntaxTree.ParseText(source);
  var root = node.GetRoot();

  var walker = new MyWalker();
  walker.Visit(root);

but the visit MethodDeclaration is never called.

To get sure I compared with the SyntaxTree Analyzer I can see that roslyn should recognize it as Method declaration. enter image description here

What am I missing?


Solution

  • I found it. I didn't have the base call in the visit class method. so just a bug of mine

    so it should be

    public override void VisitClassDeclaration(ClassDeclarationSyntax node)
    {
        [...]
        base.VisitClassDeclaration(node); // this was missing
    }