Skip to content

Instantly share code, notes, and snippets.

@JoshVarty
Last active February 10, 2020 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshVarty/1c33e136ccc9776692b8 to your computer and use it in GitHub Desktop.
Save JoshVarty/1c33e136ccc9776692b8 to your computer and use it in GitHub Desktop.
var tree = CSharpSyntaxTree.ParseText(@"
class MyClass
{
int myField = 0;
public int MyProperty {get; set;}
public void MyMethod() { }
}");
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
//Get declarations
var property = tree.GetRoot().DescendantNodes().OfType<PropertyDeclarationSyntax>().Single();
var method = tree.GetRoot().DescendantNodes().OfType<PropertyDeclarationSyntax>().Single();
var field = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single();
//Get symbols
var propertySymbol = model.GetDeclaredSymbol(property);
var methodSymbol = model.GetDeclaredSymbol(method);
var fieldSymbol = model.GetDeclaredSymbol(field);
@vikas379
Copy link

Hi @JoshVarty,
Line no. 16 should have MethodDeclarationSyntax instead of PropertyDeclarationSyntax

Cheers,
Vikas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment