Sam Holder
Sam Holder

Reputation: 32936

With roslyn, how can I get the symbol for a specific method on a type defined in a metadata reference?

My solution builds ok in roslyn and so all types should be resolved

I'm able to get the type defined in a metadata assembly like so:

string typeName = "MyCompany.MyLibrary.MyType`1";
var theType = compilation.GetTypeByMetadataName(typeName);

and when I query the member names I see the method on the type, and I want to find all references to that method, but I can't figure out how I'm supposed to get the symbol for the method. When I try

var symbols = compilation.GetSymbolsWithName("MethodName");

it always returns 0.

And I can't see anyway to navigate from my type to the symbols underneath it in the tree.

I can't get the semantic model and find the symbol that way because I don't have a syntax tree for the metadata assembly.

I can find the symbol if I find an implementation in the current solution when overrides this method, but I don't want to have to go through that, I'd like to just go directly to the symbol.

Upvotes: 3

Views: 1302

Answers (1)

George Alexandria
George Alexandria

Reputation: 2936

ITypeSymbol has GetMembers which returns all members from type as ISymbol by a specified name (second overload). So you just need to check, that the set of returned members contains at least an one IMethodSymbol (or you may add a more specific check if you want):

string typeName = "MyCompany.MyLibrary.MyType`1";
var theType = compilation.GetTypeByMetadataName(typeName);
if (!(theType is null))
{
    foreach (var member in theType.GetMembers("MethodName"))
    {
        if (member is IMethodSymbol method) //may check that method has a special parameters, for example
        {
            // you found the first "MethodName" method
        }
    }
}

Upvotes: 2

Related Questions