Extract class information

733 Views Asked by At

I need to create some kind of documentation for my code. For this I have to extract information from few hundreds of C# classes.

Basically each class contains some method MyMethod. In this method there is maybe a switch case with few cases. Overall code structure is like this

MyMethod()
{
..some code..

switch (variable)
    case "A":
          break;
    case "B":
          break;

..some other code..
}

All I need is lookup for a switch case in MyMethod and extract case values.

So far I came up with option to use Roslyn or Nrefactory to parse all .cs files and then using ASTs look into them to extract AST nodes I need.

But this approach looks a bit odd, since the task can PROBABLY be perfectly automated in some other way. I have clear files structure, I know exactly method name I need to check, and there is exactly one switch statement inside of it. Always.

Are there any other convenient ways to extract information and generate this documentation ?

2

There are 2 best solutions below

0
On BEST ANSWER

Only things that I can think of is to either parse the C# files or parse the compiled IL using Mono.Cecil or similar. In the former case, my friend has written a C# parser available here.

Of course if you are going the parse-cs way, Roslyn is now a suitable option as you mentioned. there is a quick introduction here: http://www.filipekberg.se/2011/10/20/using-roslyn-to-parse-c-code-files/

0
On

You want to parse C# code. Using anything other than a proper C# parser (like Roslyn or NRefactory) will lead to very brittle code.

For example, you'll start by searching for the string void MyMethod(). Then you'll find that one type has void MyMethod( ) instead, so you change the search to the regex void\s+MyMethod\s*\(\s*\). Then some file will contain void MyMethod() in a comment or a string, so you'll write code that (imperfectly) detects comments and strings.

After a while, you reach a point where you've gradually built a very primitive C# parser and you're dreading what kind of code will it need to support next.

If you start with a proper C# parser, you won't have these kinds of problems. So, unless the performance of that is totally unacceptable for you, I think you should use it.