I’m trying to analyse the primary constructor of a class but I can’t find how. It should be possible to find it in the syntax tree, I don’t want to create the semantic model.
The code is pretty trivial.
string testCode = @"
public class TestClass(int someInt)
{
}";
var tree = CSharpSyntaxTree.ParseText(testCode);
var root = tree.GetRoot();
var cls = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single();
var primaryCtr = cls.DescendantNodes()
.OfType<PrimaryConstructorBaseTypeSyntax>()
.FirstOrDefault();
Console.WriteLine(primaryCtr != null ? "primaryCtr FOUND" : "NOT FOUND!");
This code outputs NOT FOUND!
and I could not find any other way how to find it.
Let’s see what the tree contains.
foreach (var item in root.DescendantNodes())
Console.WriteLine(item.GetType().Name);
This outputs the following:
ClassDeclarationSyntax
ParameterListSyntax
ParameterSyntax
PredefinedTypeSyntax
That was little surprising but I guess it makes sense that in the parsed context the primary constructor is nothing else than a list of parameters.
So to detect the primary constructor I have to look for a ParameterListSyntax
that is immediate descendant of the ClassDeclarationSyntax
.