Christo S. Christov
Christo S. Christov

Reputation: 2309

Get SyntaxTree from TypeSyntax

Is there an easy way to get to the SyntaxTree of the document in which a specific TypeSyntax is defined?

I can get the Identifier property whenever the TypeSyntax is IdentifierNameSyntax but I still can't get a secure way to visit the SyntaxTree of the Type.

Update:

Here's what I currently have :

var right = exp.Right as ObjectCreationExpressionSyntax;
                    if (right != null) {
                        Compilation comp;
                        if ((comp = activeProject.GetCompilationAsync().Result) != null) {
                            bool cst = comp.ContainsSyntaxTree(right.Type.SyntaxTree);
                            var semanticModel = comp.GetSemanticModel(right.Type.SyntaxTree);
                            var typeInfo = semanticModel.GetTypeInfo(right.Type);
                            Console.WriteLine();
                            //var c = comp.GetSemanticModel(comp);
                            //var model = c.GetTypeInfo(right.Type as TypeSyntax);
                            //var v = model.Type.DeclaringSyntaxReferences;
                        }
                    }

Upvotes: 2

Views: 727

Answers (1)

SLaks
SLaks

Reputation: 888067

To read type info, you need to get the semantic model.

Call SemanticModel.GetSymbolInfo(TypeSyntax) to get the SymbolInfo, then read the DeclaringSyntaxReferences property of the symbol.

Note that partial classes may have multiple symbols defined in multiple files.

Upvotes: 1

Related Questions