Reputation: 6152
If I use a type alias in my source:
using Something = DateTime;
And then later I refer to its members:
var date = Something.Now;
When I analyse the syntax tree with Roslyn, I will have a SimpleMemberAccessExpression for Something without knowing it's just an alias for DateTime.
Is there a way to know Something is an alias semantically? I wouldn't want to parse the whole file and keep track of all the aliases.
Upvotes: 2
Views: 1047
Reputation: 1010
To attain the Type of the member you need to resolve it using the semantic model.
For the following piece of code I assume you have a Document or can otherwise obtain the SyntaxTree and the SemanticModel:
public static async Task GetNameFromDocument(Document document)
{
var syntaxTree = await document.GetSyntaxTreeAsync();
var semanticModel = await document.GetSemanticModelAsync();
var root = syntaxTree.GetRoot();
MemberAccessExpressionSyntax member = GetMemberAccessExpressionSyntax(root);
if (member != null)
{
var firstChild = member.ChildNodes().ElementAt(0);
var typeInfo = semanticModel.GetTypeInfo(firstChild).Type as INamedTypeSymbol;
var typeName = typeInfo.Name;
}
}
public static MemberAccessExpressionSyntax GetMemberAccessExpressionSyntax(SyntaxNode node)
{
return node.DescendantNodes().Where(curr => curr is MemberAccessExpressionSyntax)
.ToList().FirstOrDefault() as MemberAccessExpressionSyntax;
}
You use the SyntaxTree to find your Expression - however you see fit (so you have to replace GetMemberAccessExpressionSyntax) - and can afterwards use the semantic model to resolve the Type of the MemberAccessExpression.
The first Child of a MemberAccessExpressionSyntax should always be the accessed member so you can take the node and attain its type using the semantic model. The provided Type is the acutal type rather than the alias - typeName would correspond to DateTime
Upvotes: 4