Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create/execute code in run-time in C#?

Tags:

c#

.net

runtime

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

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

Edit: As I understand CodeDOM allows you to compile C# code into EXE file rather than "just" executing it. Here's some background information and why (as far as I can tell) this isn't the best option for me. I'm creating an application that will have to execute such a dynamically created code quite a lot [for the record - it's for academic research, not a real-world application, thus this cannot be avoided]. Therefore, creating/executing thousands of dynamically created EXEs aren't really efficient. Secondly - all dynamic code fragments returns some data that is hard to read from separately running EXE. Please let me know if I'm missing something.

As for DynamicMethod approach, pointed out by Jon Skeet, everything would work like a charm if there would be an easier way to write the code itself rather than low level IL code.

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

string x = "_some c# code here_";
var result = Exec(x);
like image 801
rexem Avatar asked Jan 20 '23 23:01

rexem


2 Answers

Absolutely - that's exactly what I do for Snippy for example, for C# in Depth. You can download the source code here - it uses CSharpCodeProvider.

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

like image 185
Jon Skeet Avatar answered Jan 31 '23 15:01

Jon Skeet


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

I believe they use the CSharpCodeProvider.

like image 26
Oded Avatar answered Jan 31 '23 15:01

Oded