Getting Class FullName (including namespace) from Roslyn ClassDeclarationSyntax
c#, roslyn
Solution
you can do this using the helper class I wrote:
NamespaceDeclarationSyntax namespaceDeclarationSyntax = null;
if (!SyntaxNodeHelper.TryGetParentSyntax(classDeclarationSyntax, out namespaceDeclarationSyntax))
{
return; // or whatever you want to do in this scenario
}
var namespaceName = namespaceDeclarationSyntax.Name.ToString();
var fullClassName = namespaceName + "." + classDeclarationSyntax.Identifier.ToString();
and the helper:
static class SyntaxNodeHelper
{
public static bool TryGetParentSyntax<T>(SyntaxNode syntaxNode, out T result)
where T : SyntaxNode
{
// set defaults
result = null;
if (syntaxNode == null)
{
return false;
}
try
{
syntaxNode = syntaxNode.Parent;
if (syntaxNode == null)
{
return false;
}
if (syntaxNode.GetType() == typeof (T))
{
result = syntaxNode as T;
return true;
}
return TryGetParentSyntax<T>(syntaxNode, out result);
}
catch
{
return false;
}
}
}
There is nothing overly complex going on here... it makes sense that the namespace would be "up" the syntax tree (because the class is contained within the namespace) so you simply need to travel "up" the syntax tree until you find the namespace and append that to the identifier of the `ClassDeclarationSyntax`.
Problem
I've a ClassDeclarationSyntax from a syntax tree in roslyn. I read it like this: ``` var tree = SyntaxTree.ParseText(sourceCode); var root = (CompilationUnitSyntax)tree.GetRoot(); var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>(); ``` The identifier only contains the name of the class but no information about the namespace, so the fullType Name is missing. Like "MyClass" but noch "Namespace1.MyClass" what is the recommended way to get the namespace / FulltypeName of the Syntax?