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();
    });
});
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With