Programmatically access the CIL for a .NET type

Posted by Jordão on Stack Overflow See other posts from Stack Overflow or by Jordão
Published on 2010-05-05T15:44:23Z Indexed on 2010/05/05 15:48 UTC
Read the original article Hit count: 482

Filed under:
|
|

Is there a straighforward library that I can use to access the CIL for a .NET type? Let me demonstrate what I want the fictitious CilExtractor to do:

[Serializable]
public class Type_For_Extract_Cil_Test {

  private int _field = 3;

  public int Method(int value) {
    checked {
      return _field + value;
    }
  }

}

[Test]
public void Extract_Cil_For_Type_Test() {
  string actualCil = CilExtractor.ExtractCil(typeof(Type_For_Extract_Cil_Test));
  string expectedCil = @"
    .class public auto ansi serializable beforefieldinit Type_For_Extract_Cil_Test
      extends [mscorlib]System.Object
    {
      .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
      {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: ldc.i4.3 
        L_0002: stfld int32 Type_For_Extract_Cil_Test::_field
        L_0007: ldarg.0 
        L_0008: call instance void [mscorlib]System.Object::.ctor()
        L_000d: ret 
      }

      .method public hidebysig instance int32 Method(int32 'value') cil managed
      {
        .maxstack 8
        L_0000: ldarg.0 
        L_0001: ldfld int32 Type_For_Extract_Cil_Test::_field
        L_0006: ldarg.1 
        L_0007: add.ovf 
        L_0008: ret 
      }

      .field private int32 _field
    }";
  // indentations and code formatting issues apart, this should succeed
  Assert.AreEqual(expectedCil, actualCil);
}

I know I can do this with Mono.Cecil or Reflector, but I also know I have to write a lot of code to achieve this. Since Reflector already does this on its UI, isn't there a simple way to access this functionality, like with a simple method call? Are there other libraries that are better suited to this specific scenario?

© Stack Overflow or respective owner

Related posts about cil

Related posts about reflection