doorman
doorman

Reputation: 16969

Extract called method information using roslyn

I need to get information about a method call into a DLL using Roslyn. For example, I have the following method where dllObject is part of a DLL file.

 public void MyMethod()
 {
     dllObject.GetMethod();
 }

Is it possible to extract the method information for GetMethod such as it´s name, class name and assembly name.

Upvotes: 1

Views: 1836

Answers (1)

JoshVarty
JoshVarty

Reputation: 9426

Yes, you need to first search your syntax tree for an InvocationExpressionSyntax and then use the SemanticModel to retrieve the full symbol for it which should contain information about its full name (.ToString()), class (.ContainingType) and assembly (.ContainingAssembly).

The following example is self contained so it doesn't use an external DLL but the same approach should work for external types.

var tree = CSharpSyntaxTree.ParseText(@"
    public class MyClass {
            int Method1() { return 0; }
            void Method2()
            {
                int x = Method1();
            }
        }
    }");

var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);

//Looking at the first invocation
var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var invokedSymbol = model.GetSymbolInfo(invocationSyntax).Symbol; //Same as MyClass.Method1

//Get name
var name = invokedSymbol.ToString();
//Get class
var parentClass = invokedSymbol.ContainingType;
//Get assembly 
var assembly = invokedSymbol.ContainingAssembly;

I wrote a short blog post about the Semantic Model a few years ago that you might find helpful.

Upvotes: 6

Related Questions