lorond
lorond

Reputation: 3896

Emit IL OpCodes from C# source code

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());

Upvotes: 2

Views: 1272

Answers (2)

TDaver
TDaver

Reputation: 7264

Roslyn should be something close to this...

Upvotes: 1

Viacheslav Smityukh
Viacheslav Smityukh

Reputation: 5843

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

Upvotes: 1

Related Questions