I am using Roslyn's September 2012 CTP.
What is the most elegant way to get unresolved types in a c# code document? Eg. Type Guid requires the System namespace. Currently I have something like this:
var semanticModel = (SemanticModel)document.GetSemanticModel();
var tree = (SyntaxTree)document.GetSyntaxTree();
//get unresolved types
var unresolvedTypes = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>()
.Where(x => semanticModel.GetSymbolInfo(x).Symbol == null);
Is it correct to use IdentifierNameSyntax and GetSymbolInfo?
Also what is the difference between GetSymbolInfo and GetTypeInfo, they both look very similar to me.
There are several questions here.
Q: Is it correct to use IdentifierNameSyntax
?
A: You probably want to use SimpleNameSyntax
to handle resolving generic types. Also, you may not want to look at ALL SimpleNameSyntax
elements. You will get false positives for things that are not actually in a type context (for example, imagine some code like var x = Console();
Q: Is it correct to use GetSymbolInfo
and check for null?
A: Yes, this is the right thing to check here.
Q: What is the difference between GetSymbolInfo
and GetTypeInfo
?
A: For a syntax that represents a type name, there is no difference. However, for arbitrary expressions GetSymbolInfo
represents the specific symbol of the expression (for example, method call, indexer access, array access, overloaded operator, etc), and GetTypeInfo
represents the resulting type (so that you would know what type to generate if you were adding a declaration for the expression). Take for example the InvocationExpressionSyntax
for "myString.GetHashCode()
". GetSymbolInfo
would return the method symbol for GetHashCode()
, while GetTypeInfo
would return System.Int32
.
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