Created
October 30, 2014 04:12
-
-
Save JoshVarty/fd828fc224c2f6d85fad to your computer and use it in GitHub Desktop.
Demonstrating basic usage of Roslyn's Semantic Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tree = CSharpSyntaxTree.ParseText(@" | |
public class MyClass { | |
int Method1() { return 0; } | |
void Method2() | |
{ | |
int x = Method1(); | |
} | |
} | |
}"); | |
var Mscorlib = new MetadataFileReference(typeof(object).Assembly.Location); | |
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