Search code examples
c#roslynmicrosoft.codeanalysis

Why can't I get all ObjectCreationExpressionSyntax if initialized as null?


So, I have a MethodDeclarationSyntax node that I'm passing to a CSharpSyntaxWalker, with the following overrides

        public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
    {
        LiteralExpressionCollector literalCollector = new LiteralExpressionCollector();
        literalCollector.Visit(node.ArgumentList);
        if (literalCollector.Literals.Count > 0)
            Creations.Add(node, literalCollector.Literals);
    }

        public override void VisitAssignmentExpression(AssignmentExpressionSyntax node)
    {
        LiteralExpressionCollector literalCollector = new LiteralExpressionCollector();
        var assigment = node.ChildNodes().FirstOrDefault(l => l is LiteralExpressionSyntax);
        if(assigment != null)
            literalCollector.Visit(assigment);
        if (literalCollector.Literals.Count > 0)
            Assigments.Add(node, literalCollector.Literals);

    }

It catches all ObjectCreationExpressionSyntax in the following form:

ResolveBomForMaterialInput rbfmiInput = new ResolveBomForMaterialInput()

But not the following:

FlowStructureScenario flowScenario = null;
flowScenario = new FlowStructureScenario("F", "F:3");

Any idea of why this is happening? I don't think it matters but I'm using SyntaxWalkerDepth.Token as depth.

Currently using the version: Microsoft.CodeAnalysis 1.3.2


Solution

  • The issue is that your code in VisitAssignmentExpression stops the syntax walk as soon as it encounters an assignment expression. If you want to continue walking its child nodes, you can add base.VisitAssignmentExpression(node); to the method.