Getting zero value for ITypeSymbol
I am writing some tests and I need to get the ITypeSymbol. This is how I do it:
private async Task<ITypeSymbol> GetTypeSymbol(string file, TextSpan span)
{
var code = File.ReadAllText(file);
var tree = CSharpSyntaxTree.ParseText(code);
var compilation = CSharpCompilation.Create(
this.GetType().Assembly.GetName().Name,
syntaxTrees: new[] { tree },
references: new[]
{
MetadataReference.CreateFromAssembly(typeof(object).Assembly))
});
var model = compilation.GetSemanticModel(tree);
var root = await tree.GetRootAsync().ConfigureAwait(false);
return model.GetTypeInfo(root.FindNode(span)).Type;
}
For some reason, the Type property on the last line is always null, even if I pass code from a file that looks like this:
public class AClass { }
To be clear, the file reads fine, it parses correctly, the compilation is done, I can get the model, and FindNode () will find the correct ClassDeclarationSyntax node I'm looking for. GetTypeInfo () returns, but both type and ConvertedType are null. I kind of expected it to really matter. Is my expectation correct? If so, what am I doing wrong to make the Type property null?
+3
source to share
1 answer
In fact, it looks like GetDeclaredSymbol () ( How to get the ancestor of a module in the roslyn semantic model? ) Is the way to go. It works fine.
+3
source to share