public void FindAllInvocationsOfAMethod()
{
var tree = SyntaxTree.ParseText(@"
class C1
{
public void M1() { M2(); }
public void M2() { }
}
class C2
{
public void M1() { M2(); new C1().M2(); }
public void M2() { }
}
class Program
{
static void Main() { }
}");
var mscorlib = MetadataReference.CreateAssemblyReference("mscorlib");
var compilation = Compilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { mscorlib });
var model = compilation.GetSemanticModel(tree);
// Get MethodDeclarationSyntax corresponding to method C1.M2() above.
MethodDeclarationSyntax methodDeclaration = tree.GetRoot()
.DescendantNodes().OfType<ClassDeclarationSyntax>().Single(c => c.Identifier.ValueText == "C1")
.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(m => m.Identifier.ValueText == "M2");
// Get MethodSymbol corresponding to method C1.M2() above.
MethodSymbol method = model.GetDeclaredSymbol(methodDeclaration);
// Get all InvocationExpressionSyntax in the above code.
var allInvocations = tree.GetRoot()
.DescendantNodes().OfType<InvocationExpressionSyntax>();
// Use GetSymbolInfo() to find invocations of method C1.M2() above.
var matchingInvocations = allInvocations
.Where(i => model.GetSymbolInfo(i).Symbol.Equals(method));
Assert.AreEqual(2, matchingInvocations.Count());
}