koraytaylan koraytaylan - 4 months ago 18
C# Question

Can I use reflection to inspect the code in a method?

I'm playing around with the C# reflection API. I can easily load

information of classes, methods etc. in an assembly, however, now I wonder how can I load and read the code inside a method?


Basic Answer:

You can't with the reflection API (System.Reflection).

The reason is that the reflection api is designed to work on Metadata (Type of Classes, Name and Signature of Methods, ...) but not on the data level (which would be the IL-stream itself).

Extended Answer:

You can emit (but not read) IL with System.Reflection.Emit (e.g. ILGenerator Class).

Through MethodInfo.GetMethodBody() you can get the binary IL-stream for the implementation of a method. But thats usually completely useless by itself.

There are external libraries (like Cecil) that you can use to read/modify/add/delete code inside a method.