Reflection in .NET 2.0 ships with a new class MethodBody, which "provides access
to information about the local variables and exception-handling clauses in a method
body, and to the Microsoft intermediate language (MSIL) that makes up the method
body". (Thanks to Glenn, who wrote
this in the MSDN doc; I simply copy & paste it). The only one method
inside this class (others are properties) is:
which returns us a byte array containing IL content for this method body.
Recently we got some questions related to reflecting IL stream: users want to check
where a specific method was used; or try to build a call graph inside an assembly;...
Reflection currently does not support this directly. Lutz Roeder's awesome tool
- .NET Reflector can indeed show
the call/callee graph for each method. I used to have the source code for his ILReader,
and noticed it did not use Reflection APIs (so for sure we can read IL without reflection
A code sketch below shows how we can use classes in the Reflection/Emit namespace
(and other useful APIs provided in .NET 2.0) to read IL instructions.
Standard ECMA-335 is the authoritative resource to understand IL, MethodBody
format and other CLI topics if you want to know more of them.
Few comments here:
Then I can consume the ILInstruction sequence in C# as follows: