Reputation: 12766
I want to use Roslyn to get all types used in a piece of code. I started with the following SyntaxWalker:
public class DependenciesCollector : SyntaxWalker
{
public override void VisitIdentifierName(IdentifierNameSyntax node)
{
if (!(node.Parent is UsingDirectiveSyntax))
{
Console.WriteLine(node.PlainName);
}
base.VisitIdentifierName(node);
}
public override void VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
Console.WriteLine(node.Expression + "." + node.Name);
base.VisitMemberAccessExpression(node);
}
}
But instead of showing me only the (part) types used, it also shows the using statements while I (as you can see) tried not to show the using statements. Can you tell me what is wrong with this code?
In short: I want only the types excluding namespaces. Is this even possible? (Things like System.Console are ok, System not)
Upvotes: 2
Views: 2404
Reputation: 2016
I think you may be a bit confused. This code is not going to show you types at all. It is going to show you the identifier names used in source, and any of the member access expressions (a.b). Some of these may be type names, but most likely they are just code expressions.
If in a method body your write:
System.Console.WriteLine("x")
Syntactically, the compiler doesn't know that System.Console
is a type name yet. It parses the pair as a member access expression, no different than the Console.WriteLine
part.
In other syntactic locations, the compiler knows better. For example, in a local declaration:
Syntax.Console x = null;
The compiler knows that Syntax.Console
refers to a type, so it is parsed as a qualified name, not a member access expression.
If you really want to know what types are used by the code, you should be using the semantic model to discover what type symbols these dotted names correspond to.
Upvotes: 2