Bread
Bread

Reputation: 443

Finding SyntaxNode of an ISymbol

Given a SemanticModel instance and an ISymbol assosiated with it, is it possible to get SyntaxNode of the ISymbol?

Basicly the opposite of GetDeclaredSymbol method of SemanticModel

the only way i am aware of is searching the SyntaxTree root with a predicate, is there a way to do it with less code?

Upvotes: 3

Views: 292

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

In order to get the SyntaxNode declaration(s) from a ISymbol, use ISymbol.DeclaringSyntaxReferences.

Notice that it can return multiple references (f.e. when you've got a partial declaration) or none (when it is declared externally).

A small example:

var syntaxReference = propSymbol.DeclaringSyntaxReferences
                                .First()
                                .GetSyntax();

GetSyntax() will return a SyntaxNode so you should still cast it to the exact type you're interested in.

Upvotes: 8

Related Questions