Roslyn Get Method Declaration from InvocationExpression

If you need the declaration of the method that you are calling, you can get that as follows.

In the first step, you find out what method it is that is being called:

var methodSymbol = context
    .SemanticModel
    .GetSymbolInfo(invocation, context.CancellationToken)
    .Symbol as IMethodSymbol;

Remember that there are various reasons why the methodSymbol may be null (e.g. you were invoking a delegate, not a method), so test for that.

Then you can find the declaring syntax references, and take the first one:

var syntaxReference = methodSymbol
    .DeclaringSyntaxReferences
    .FirstOrDefault();

This can be null as well, e.g. when you were calling a method from another assembly, so test for that.

Finally:

var declaration = syntaxReference.GetSyntax(context.CancellationToken);

That gives you the syntax. Should you need a semantic model for that declaration, you can get that using

var semanticModel = context.Compilation.GetSemanticModel(declaration.SyntaxTree);

Leave a Comment