Extract method names from .CS code files

2.1k views Asked by At

I want to extract all the method declarations from a standard csharp .CS code file into an array, ignoring any classes. I'll be using this in validation project later which is rather complicated to explain at the moment.

So lets say our csharp code file contains the following methods:

using System.Blah;
namespace abc
{
   public static class myclass
   {
      public void MethodA()
      {
        //... lines of code
      }
      public void MethodB()
      {
        //... lines of code
      }
   }
}

I'd like to get that into an array which can be outputted as follows

1. MethodA()
2. MethodB()

Is there code you can share or know of that would allow me to easily do this ?

1

There are 1 answers

3
NicoE On BEST ANSWER

Not sure of the use - are you treating the cs as code (thus need to validate that it actually compiles and execute methods) or simply getting a list of method signatures and treating the cs file thus as text.

If the latter and treating the cs as text then using regex will allow you to obtain the list of methods (name and attributes as per your example) based on a regex pattern

See this answer for a similar question relating to java methods. The syntax is the same between the languages as far as the pattern is concerned: https://stackoverflow.com/a/847507/4989423

You'll need to run the regex in a separate utility you write that reads the cs files in question.