I\'ve got a .cs file named \'test.cs\' which essentially looks like:
namespace test
{
public class TestClass
{
public void Hello()
{
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 variableDeclaration in variableDeclarations)
{
var symbolInfo = semanticModel.GetSymbolInfo(variableDeclaration.Declaration.Type);
var typeSymbol = symbolInfo.Symbol; // the type symbol for the variable..
}
}
See the unit test called TestGetDeclaredSymbolFromLocalDeclarator in the Roslyn source tree.