Search code examples
roslyn

How to get fields and properties accessed by a method of same class?


I tried to look through the syntax tree, but the information is not sufficient enough, so I created a compilation and got the semantic model of the syntax tree. Now I can get properties and fields declarations using OfType<T> extension method where T is PropertyDeclarationSyntax or FieldDeclarationSyntax.

Inside a method.Body.Statements I thought I could look for symbols representing the ones I got from OfType<T>. But I am having a hard time figuring that part out. The syntax tree just identifies the symbol as "IdentifierName", which is not much helpful..

If this is not the correct way of looking at it, please let me know.


Solution

  • Use SemanticModel.GetDeclaredSymbol() on the PropertyDeclartionSyntax or the one of the VariableDeclaratorSyntax inside the FieldDefinitionSyntax. Then use SemanticModel.GetSymbolInfo() on the identifiers and see if they match. (Note that you should use ISymbol.Equals as you might not get reference equal results.