Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 method symbol
var methodSyntax = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First();
var methodSymbol = model.GetDeclaredSymbol(methodSyntax);
Console.WriteLine(methodSymbol.ToString()); //MyClass.Method1()
Console.WriteLine(methodSymbol.ContainingSymbol); //MyClass
Console.WriteLine(methodSymbol.IsAbstract); //false
//Looking at the first invocation
var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var invokedSymbol = model.GetSymbolInfo(invocationSyntax).Symbol; //Same as MyClass.Method1
Console.WriteLine(invokedSymbol.ToString()); //MyClass.Method1()
Console.WriteLine(invokedSymbol.ContainingSymbol); //MyClass
Console.WriteLine(invokedSymbol.IsAbstract); //false
Console.WriteLine(invokedSymbol.Equals(methodSymbol)); //true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment