Finding all references to a method with Roslyn

You’re probably looking for the SymbolFinder class and specifically the FindAllReferences method.

It sounds like you’re having some trouble getting familiar with Roslyn. I’ve got a series of blog posts to help people get introduced to Roslyn called Learn Roslyn Now.

As @SLaks mentions you’re going to need access to the semantic model which I cover in Part 7: Introduction to the Semantic Model

Here’s a sample that shows you how the API can be used. If you’re able to, I’d use MSBuildWorkspace and load the project from disk instead of creating it in an AdHocWorkspace like this.

var mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var ws = new AdhocWorkspace();
//Create new solution
var solId = SolutionId.CreateNewId();
var solutionInfo = SolutionInfo.Create(solId, VersionStamp.Create());
//Create new project
var project = ws.AddProject("Sample", "C#");
project = project.AddMetadataReference(mscorlib);
//Add project to workspace
ws.TryApplyChanges(project.Solution);
string text = @"
class C
{
    void M()
    {
        M();
        M();
    }
}";
var sourceText = SourceText.From(text);
//Create new document
var doc = ws.AddDocument(project.Id, "NewDoc", sourceText);
//Get the semantic model
var model = doc.GetSemanticModelAsync().Result;
//Get the syntax node for the first invocation to M()
var methodInvocation = doc.GetSyntaxRootAsync().Result.DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var methodSymbol = model.GetSymbolInfo(methodInvocation).Symbol;
//Finds all references to M()
var referencesToM = SymbolFinder.FindReferencesAsync(methodSymbol,  doc.Project.Solution).Result;

Leave a Comment