tags:

views:

76

answers:

4

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

+2  A: 

If inline IL (in the same spirit of inline assembly supported by C and C++ compilers) is what you're looking for, this can be achieved using post-compilation round-trip compiling.

Mike Stall has once written a tool for that, as far as I know it's fairly mature:

Other than that, you could use F# which supports Inline IL.

Johannes Rudolph
A: 

The tool you need is called Cecil and is a part of the Mono project.

You can get more information about it here: http://www.mono-project.com/Cecil

Quoted from the website above:

Cecil is a library written by Jb Evain (http://evain.net/blog/) to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format.

In simple English, with Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly.

Pierre 303
A: 

DynamicMethod is the lightweight way to accomplish this at runtime.

The Microsoft C# compiler doesn't support injection of IL at compile-time, but a code-weaving tool could do so as a post-compile step.

Ben Voigt