Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve all (and only) class variables?

Tags:

c#

roslyn

I need to extract all class variables. But my code returns all variables, including variables declared in methods (locals). For example:

class MyClass
{
    private int x;
    private int y;

    public void MyMethod()
    {
        int z = 0;
    }
}

I need to get only x and y but I get x, y, and z. My code so far:

SyntaxTree tree = CSharpSyntaxTree.ParseText(content);
IEnumerable<SyntaxNode> nodes = ((CompilationUnitSyntax) tree.GetRoot()).DescendantNodes();

List<ClassDeclarationSyntax> classDeclarationList = nodes
    .OfType<ClassDeclarationSyntax>().ToList();

classDeclarationList.ForEach(cls =>
{
    List<MemberDeclarationSyntax> memberDeclarationSyntax = cls.Members.ToList();
    memberDeclarationSyntax.ForEach(x =>
    {
        //contains all variables
        List<VariableDeclarationSyntax> variables = x.DescendantNodes()
           .OfType<VariableDeclarationSyntax>().ToList();
    });
});
like image 680
bluray Avatar asked Apr 29 '16 15:04

bluray


1 Answers

You should filter for FieldDeclarationSyntax which, evidently, only refers to fields (also known as class variables).

I'm not sure why you're going through the extra hoop of MemberDeclarationSyntax though: cls.DescendantNodes().OfType<FieldDeclarationSyntax>() should work just fine since you're still going to traverse the tree anyway.

Afterwards, FieldDeclarationSyntax.Declaration holds what you're interested in: the VariableDeclarationSyntax.

like image 199
Jeroen Vannevel Avatar answered Oct 17 '22 14:10

Jeroen Vannevel