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?
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.
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'sif else
orswitch
.Other option, is of course to parse the text in yourself and find what you want..