1

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.

1 Answer 1

2

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.

UPDATE

I found even a better way.

string testCode = @"
public class TestClass(int someInt)
{

}";

var tree = CSharpSyntaxTree.ParseText(testCode);
var root = tree.GetRoot();
var cls = root.DescendantNodes().OfType<ClassDeclarationSyntax>().Single();

if(cls.ParameterList == null)
    Console.WriteLine("NO PRIMARY CTR");
else
    Console.WriteLine("PRIMARY CTR FOUND");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.