Is it possible to create / execute code at runtime in C #?

I know that you can dynamically create a .NET assembly using Emit, System.Reflection and manually created IL code, as shown here .

But I was wondering if it is possible to dynamically create and execute C # code in real time in a running application. Thanks for any input or ideas.

Edit: As far as I understand, CodeDOM allows you to compile C # code into an EXE file, and not "just" execute it. Here is some background information and why (as far as I can tell) this is not the best option for me. I am creating an application that will have to execute such dynamically generated code quite a lot [for writing, this is for academic research, and not for a real application, so this cannot be avoided). Therefore, creating / executing thousands of dynamically created EXE files is inefficient. Secondly, all fragments of dynamic code return some data that is difficult to read from a separately working EXE. Please let me know if I missed something.

As for the DynamicMethod approach John Skeet pointed out, everything will work as a charm if there is an easier way to write the code itself, rather than a low-level IL code.

In other words (very roughly) I need something like this:

string x = "_some c# code here_"; var result = Exec(x); 
+4
source share
4 answers

Absolutely - this is what I do for Snippy, for example, for C # in Depth. Here you can download the source code - it uses CSharpCodeProvider .

There is also the possibility of building expression trees, and then compiling them in delegates using DynamicMethod or DLR in .NET 4 ... all kinds of things.

+8
source

Yes it is. There are several applications that do just that - see LinqPad and Snippy .

I believe that they use CSharpCodeProvider .

+1
source

Yes. See this MSDN page for using CodeDOM .

Sample code extracted from the above mention page:

 CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!") ); start.Statements.Add(cs1); 
0
source

You can use CodeDom to generate code and create in memory assemblies based on this generated code. You can then use THose in the current application.

Here is a short link to the msdn link, this is pretty extensive material.

MSDN: Using CodeDom

0
source

All Articles