Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all visible local variable names within a scope with Roslyn (Microsoft CodeAnalysis)

Tags:

c#

roslyn

(Please note: This is not about run-time reflection/metainfo)

I am writing a concrete implementation of Roslyn CSharpSyntaxVisitor

When implementing the VisitIdentifierName

public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax name)
{
   var symbolInfo = _semanticModel.GetSymbolInfo(name);
   var fieldSymbol = symbolInfo.Symbol as IFieldSymbol;
   if (fieldSymbol != null)
   {
       // Here I would like to get all the local variable names what are visible
       // in the very same scope where this field IdentifierNameSyntax under visiting resides
       // We can suppose that _semanticNodel for the Document is available.
   }
}
like image 344
g.pickardou Avatar asked May 08 '14 11:05

g.pickardou


1 Answers

Call SemanticModel.LookupSymbols() (source), then filter for local variables.

You may also want to filter out locals declared after that location; see this code.

like image 179
SLaks Avatar answered Nov 13 '22 11:11

SLaks