Julio Kriger
Julio Kriger

Reputation: 59

Generate dynamic code from string with Reflection.Emit

I have stored some C# code in a database table.

I have the whole code of a base class in a string.

With the stored C# code in hand, I add to the class a method named m1 that contains a return <<some C# code>>; (the method always returns object so the C# code can be: 88 + 90, "hello world", this.ToString(), etc.), save it to a file and compile it with CSharpCodeProvider, and run it on my program.

The stored C# code can use some methods in the base class.

This scheme works very well.

Now, I would to use Reflection.Emit to do this, to avoid the compiling step.

Is this possible, and if so, how would it be done?

Upvotes: 0

Views: 1136

Answers (1)

svick
svick

Reputation: 244837

Now, I would to use Reflection.Emit to do this, to avoid the compiling step.

That doesn't make much sense to me. If you have source code that you want to execute, you basically have two options:

  1. Compile it to some other form that can then be directly executed. (Classic compiled languages like C work like this.)
  2. Parse it into some in-memory structure and then execute that, piece by piece. (Classic interpreted languages work like this, like JavaScript in older browsers.)

Things aren't actually as simple as that these days, because of virtual machines and intermediate languages etc., but those are the basic choices.

If you don't want to use CodeDOM, that leaves you two choices (corresponding to the two options above):

  1. Parse the code and then create some executable form from it, possibly using Reflection.Emit.
  2. Parse the code and directly execute the result. You don't need Reflection.Emit for that.

Choice 1 means you would need to implement full C# compiler. Choice 2 means you would need to implement a half of C# compiler, plus an interpreter of your in-memory structure. In both cases, it would be a giant project and you wouldn't really “avoid the compiling step”.

Upvotes: 1

Related Questions