Tamas Ionut
Tamas Ionut

Reputation: 4410

How to find all usages of a MethodDeclarationSyntax in solution with Roslyn

I have the following code:

        var ws = new AdhocWorkspace();
        var project = ws.AddProject("Sample", "C#");
        ws.TryApplyChanges(project.Solution);
        string text = @"
                    class C
                        {
                            private int counter = 0;

                            public void main()
                            {
                                Do();
                            }
                            public void Do()
                            {
                                counter++;
                            }
                        }
                        class D
                        {
                            private int counter = 0;

                            public void Foo()
                            {
                                var c = new C();
                                c.Do();
                            }
                        }";
        var sourceText = SourceText.From(text);
        var doc = ws.AddDocument(project.Id, "NewDoc", sourceText);
        var model = doc.GetSemanticModelAsync().Result;
        var methodDeclaration = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<MethodDeclarationSyntax>().ToList()[1];
        var invocationExpression = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<InvocationExpressionSyntax>().ToList()[0];
        //TODO: If I replace invocationExpression with methodDeclaration IT DOES NOT WORK
        var methodSymbol = model.GetSymbolInfo(invocationExpression ).Symbol;
        //Finds all references to M()
        var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol, doc.Project.Solution).Result;

How can I find all the usages within a solution given a MethodDeclarationSyntax? (for the InvocationExpressionSyntax works ok)

Upvotes: 3

Views: 939

Answers (1)

George Alexandria
George Alexandria

Reputation: 2936

Use GetDeclaredSymbol for node declarations.

// node is methodDeclaration or invocationExpression
var methodSymbol = model.GetSymbolInfo(node).Symbol ?? model.GetDeclaredSymbol(node);

Upvotes: 4

Related Questions