How to insert CIL code to C#

Duiner picture Duiner · Jul 25, 2010 · Viewed 10.3k times · Source

Is it possible to insert IL code to C# method?

Answer

Glenn Slayden picture Glenn Slayden · May 10, 2011

I just posted a utility which allows entire C# function bodies to be automatically replaced with inline IL, using a custom attribute. Like similar utilities, this works via the ILDASM/ILASM round-trip which can be set up as a post-build step. The tool also adjusts the PDB in order to preserve single-stepping and setting breakpoints on individual IL instructions in the debugger. It's different from some of the other round-trip IL inliners in that it (only) substitutes for entire function bodies, like this:

    class MyClass
    {
        [ILFunc(@"
    .locals init ([0] int32 i_arg)
        ldc.i4.3
        ret
    ")]
        int MyFunc(int i_arg)
        {
            return 3;
        }
    };

For highly performance-critical methods, I tried using DynamicMethod to improve upon compiler-generated IL, but found that the benefit is lost due to the delegate-calling overhead. Inline IL gives the the beneft of hand-tuned IL without that hit, assuming there are no runtime customizations that you would truly need DynamicMethod for.

The complete source code is located at http://www.glennslayden.com/code/c-sharp/inline-il