Emit IL OpCodes from C# source code

1.2k views Asked by At

How to parse C# source code for generating IL opcodes, that could be used in DynamicMethod?

I want to execute code dynamically without generating unnecessary assemblies. Something like this:

var body = "return \"sample\";";
var dm = new DynamicMethod("method_" + Guid.NewGuid().ToString("N"), typeof(string), null);
var parser = new SomeKindOfCSharpParser();
parser.Emit(body, m.GetILGenerator());
2

There are 2 answers

2
TDaver On BEST ANSWER

Roslyn should be something close to this...

0
Viacheslav Smityukh On

There is no way to implement it.

You have a few ways to implement it:

  1. You can use C# compiler, but it will compile external cs file into separate assemby.
  2. You can use CodeDOM to build and compile code tree
  3. You can build Expression tree and compile it
  4. You can generate code one IL instruction after another