doorman
doorman

Reputation: 16959

Get method name of ReferencedSymbol

I have the references from a method symbol but I need to get the name of the method that is calling the method symbol. Any idea how I can extract this information from the reference object? Here is the code:

var references = SymbolFinder.FindReferencesAsync(symbol, solution).Result;

if (references != null && references.Any())
{
    foreach (var reference in references)
    {
        foreach (var location in reference.Locations)
        {
            // Get name of the method of the reference 
        }
    }
}

Upvotes: 0

Views: 208

Answers (1)

George Alexandria
George Alexandria

Reputation: 2936

You need to retrieve the SemanticModel for your reference and then you should get the innermost enclosing symbol that contains your reference:

...
foreach (var location in reference.Locations)
{
    if (location.Document.TryGetSemanticModel(out var referenceSemanticModel))
    {
        var enclosingSymbol = referenceSemanticModel.GetEnclosingSymbol(location.Location.SourceSpan.Start);
        if (!(enclosingSymbol is null))
        {
            // NOTE: if your symbol are referenced by lambda then this name 
            // would be the innermost enclosing member which contains lambda,
            // so be careful
            var name = enclosingSymbol.Name;
        }
    }
}

Upvotes: 1

Related Questions