I am trying to get type info from ObjectCreationExpressionSyntax object but failed.
Here is example that reproduce the problem (see "ti.Type is null" in code):
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
namespace RoslynExample
{
class Program
{
static void Main(string[] args)
{
string solutionPath = @"..\..\..\RoslynExample.sln";
MSBuildWorkspace workspace = MSBuildWorkspace.Create();
Solution solution = workspace.OpenSolutionAsync(solutionPath).Result;
foreach (var project in solution.Projects)
{
if (project.Name == "RoslynBugProject")
{
foreach (var document in project.Documents)
{
var compilationUnit = document.GetSyntaxRootAsync().Result;
var semanticModel = document.GetSemanticModelAsync().Result;
new MyWalker(semanticModel).Visit(compilationUnit);
}
}
}
}
}
partial class MyWalker : CSharpSyntaxWalker
{
private SemanticModel _semanticModel;
public MyWalker(SemanticModel semanticModel)
{
_semanticModel = semanticModel;
}
public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
var ti = _semanticModel.GetTypeInfo(node.Type); **<--- ti.Type is null**
base.VisitObjectCreationExpression(node);
}
}
}
"RoslynBugProject" project:
namespace RoslynBugProject
{
internal class Query
{
}
class Program
{
static void Main(string[] args)
{
var query = new Query();
}
}
}
How to get type info? Previous version of Roslyn returns not null value.
You can install the Roslyn Syntax Visualizer, which will show you the syntax tree and also let you explore the SemanticModel APIs as well.
With that installed, you can try right-clicking on nodes and asking for the type symbol:
In this case, you'll discover a couple things:
ObjectCreationExpression
itself, but not from any of its children (the "IdentifierName" or the "ArgumentList"), so this could be fixed by passing node
to GetTypeInfo
instead of node.Type
.ObjectCreationExpression
, so you could also fix your code by passing node.Type
to GetSymbolInfo
instead of GetTypeInfo
.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