Execute a string as code

Tag: c# , string , eval Author: springleng Date: 2014-04-23

I wonder if there is some method of executing a string, or convert it to a code, example: "Console.WriteLine (\" Hello \ ")";

Equivalent to 'eval' in JavaScript.

I've translated it from Translate Google.

Translate Google

Sidenote: there is a portuguese version of Stack Overflow:
possible duplicate of How can I read the properties of a C# class dynamically?
possible duplicate of in which case ChristopheD's answer (below) is best.

Other Answer1

It is a bit more contrived then using eval in some languages, but it is certainly possible to programmatically compile code.

Other Answer2

I wrote a tutorial on something very similar to this a few years ago - it is based on compiling though:

http://domscode.com/2011/02/16/new-tutorial-tdd-c-web-compiler/

Hope that helps

Other Answer3

You can try cshell: http://cshell.net/

It has a repl-based and executes c# code.

Other Answer4

I haven't tried it myself, but it seems what you're looking for is easily feasible using Roslyn ( .Net compiler service )
Take a look at eval()-like for C# using Roslyn and ScriptCS and Hosted Execution of smaller code snippets with Roslyn