5

I have the following code where I am extracting all methods from a file.

var tree = file.GetSyntaxTreeAsync().Result;
var methodDeclarations = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().ToList();

How can I only get the public functions?

1
  • 1
    You need the semantic model.
    – SLaks
    Commented Aug 22, 2018 at 17:27

1 Answer 1

8

If you're looking for methods marked as public in the file, you can use the Modifiers property of MethodDeclarationSyntax objects like so:

        var publicMethods = root.DescendantNodes()
            .OfType<MethodDeclarationSyntax>()
            .Where(method =>
                method.Modifiers.Where(modifier =>
                    modifier.Kind() == SyntaxKind.PublicKeyword)
                .Any());

If you're intereseted in all the public method of a class declared in this file, you will need to heed @Slaks's advice and use the semantic model, as public methods declared in a parent class will not show up using only the syntax analysis.

1
  • How would you do it with the semantic model? AFAICT it only gives you the DeclaredAccessibility, which isn't enough (e.g. it will classify interface method implementations as "private")
    – Clément
    Commented Apr 12, 2022 at 1:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.