To get the actual type for a variable declared using var
, call GetSymbolInfo()
on the SemanticModel
. You can open an existing solution using MSBuildWorkspace
, then enumerate its projects and their documents. Use a document to obtain its SyntaxRoot
and SemanticModel
, then look for VariableDeclarations
and retrieve the symbols for the Type
of a declared variable like this:
var workspace = MSBuildWorkspace.Create();
var solution = workspace.OpenSolutionAsync("c:\\path\\to\\solution.sln").Result;
foreach (var document in solution.Projects.SelectMany(project => project.Documents))
{
var rootNode = document.GetSyntaxRootAsync().Result;
var semanticModel = document.GetSemanticModelAsync().Result;
var variableDeclarations = rootNode
.DescendantNodes()
.OfType<LocalDeclarationStatementSyntax>();
foreach (var varDeclaration in variableDeclarations)
{
var symbolInfo = semanticModel.GetSymbolInfo(varDeclaration.Declaration.Type);
var typeSymbol = symbolInfo.Symbol; // the type symbol for the variable..
}
}