I've got a .cs file named 'test.cs' which essentially looks like:
namespace test
{
public class TestClass
{
public void Hello()
{
var x = 1;
}
}
}
I'm trying to parse this with Roslyn and get the type of x, which should be 'int', but I can only find out that it's type 'var', I can't seem to get the actual underlying type.
Here's basically what my code is now
var location = "test.cs";
var sourceTree = CSharpSyntaxTree.ParseFile(location);
var root = (CompilationUnitSyntax)sourceTree.GetRoot();
foreach (var member in root.Members)
{
//...get to a method
var method = (MethodDeclarationSyntax())member;
foreach (var child in method.Body.ChildNodes())
{
if (child is LocalDeclarationStatementSyntax)
{
//var x = 1;
child.Type.RealType()?
}
}
}
How can I get the real type of child? I've seen some things saying I should use a SemanticModel or Solution or a Workspace, but I can't seem to find out how load my test solution with Roslyn and then get the type of 'x'.
Also, I haven't been able to find any really good Roslyn documentation, it all seems to be spread out among a bunch of different versions and nothing for beginners like me. Does anyone know of an 'intro to Roslyn' or similar quickstart I could read up on?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With