0

Syntax model and Semantic model communication

I have an "InvocationExpressionSyntax" "invocation" , from which i want to access "MethodDeclarationSyntax".

Don't want just to compare their names, because the method parameters may differ.

By using semantic model I got access to Operation of invocation. By operation I have an access to TargetMethod. I would like to get MethodDeclarationSyntax of that method.

var operation = (IInvocationOperation) semanticModel.GetOperation(invocation);
var methodInvoked = operation.TargetMethod;

Community
  • 1
  • 1

1 Answers1

1

You can use this method

private static SyntaxNode GetDeclarationSyntaxNode(InvocationExpressionSyntax invocationSyntax, SemanticModel semanticModel)
{
    var methodSymbol = (IMethodSymbol) semanticModel.GetSymbolInfo(invocationSyntax).Symbol;
    var syntaxReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();

    return syntaxReference?.GetSyntax();
}

There is detailed explanation Roslyn Get Method Declaration from InvocationExpression

Edit: include null-conditional operator to code

Abedron
  • 744
  • 1
  • 6
  • 20