Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

roslyn

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.

like image 717
Sam Holder Avatar asked Dec 03 '25 18:12

Sam Holder


1 Answers

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
        }
    }
}
like image 60
George Alexandria Avatar answered Dec 06 '25 16:12

George Alexandria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!