var root = CSharpSyntaxTree.ParseText(sourceCode).GetRoot(); var methodCalls = root.DescendantNodes() .OfType() .Where(e => e.Expression.ToString() == "MyMethod");
var root = CSharpSyntaxTree.ParseText(sourceCode).GetRoot(); var transformed = root .DescendantNodes() .OfTypeIn this example, we start by parsing the input C# source code into a syntax tree as before. We then look for all nodes in the expression tree that represent a property access (MemberAccessExpressionSyntax) and transform them by adding a null check. The final line of code returns the transformed syntax tree. Both examples require the Microsoft.CodeAnalysis.CSharp package library.() .Select(e => e.Expression is ThisExpressionSyntax ? (ExpressionSyntax)e : SyntaxFactory.ConditionaAccessExpression( e.Expression, SyntaxFactory.Token(SyntaxKind.QuestionToken), e)) .ToArray(); return root.ReplaceNodes(transformed, (o, n) => n);