In C# how can I evaluate if any members of a class contain switch case or if else constructs?

158 views Asked by At

In C# how can I evaluate if any members of a class contain switch case or if else constructs? I want to check in a unit test if a class has been written with either switch...case or chained if....else.

I know how to get members of a class using reflection, but cannot find an example on the interwebs of how to get the actual code. From this SO post I found you can use MethodBase.GetMethodBody(), here. That seems great for returning a MethodBody for getting variables, but cannot find how to get information of if a switch...case or if...else exists.

Any solutions available?

1

There are 1 answers

12
Dudi Keleti On

You can't do it with reflection. Yes, you can get the method IL byte array but it's useless for your requirement.

The best way to achieve what you need is to use Roslyn, then it can't be more simple.

bool ContainsIfElseOrSwitchTest()
{
    var classToTest = // you can get it from your VS solution 
                      // or by reading the .cs file from disk
    // for example
    classToTest = CSharpSyntaxTree.ParseText(File.OpenRead(pathToFile));

    return classToTest.GetRoot().DescendantNodes().
              Any(node => node is SwitchStatementSyntax || node is IfStatementSyntax);
}

Update the answer, based on comment.

Other option is to use Mono.Cecil to get directly IL instructions without using byte array. But you must know that you can just know if the instructions contains conditions and you can't know if it's if else or switch.

Other option, is of course to parse the text in yourself and find what you want..