Tamas Ionut Tamas Ionut -4 years ago 137
C# Question

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#");
string text = @"
class C
private int counter = 0;

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

public void Foo()
var c = new C();
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)

Answer Source

Use GetDeclaredSymbol for node declarations.

// node is methodDeclaration or invocationExpression
var methodSymbol = model.GetSymbolInfo(node).Symbol ?? model.GetDeclaredSymbol(node);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download