4

Possible Duplicate:
C# eval equivalent?

Is it possible to Execute a C# command that is stored in a string variable

a thing like Dynamic query in SqlServer

3
  • I doubt that would be possible since the string wouldn't get parsed until after the program has been compiled Commented Jan 20, 2012 at 16:49
  • @xbonez: It's possible to emit your own IL and execute it so I would say it's most definitely possible. Commented Jan 20, 2012 at 16:52
  • This might look like a duplicate, but the older question specifically asks about C# 2.0, for which the answer is "no". I don't think this question should be closed as a duplicate. Commented Jan 20, 2012 at 16:56

2 Answers 2

1

There is nothing built into the current version of .NET that allows this. However the Roslyn project aims to specifically enable scenarios like this. They have a CTP out.

A simple example, (from Kirill Osenkov's blog), is:

[TestMethod]
public void SimpleEvaluationUsingScriptEngine()
{
    ScriptEngine engine = new ScriptEngine();
    int result = engine.Execute<int>("1 + 2");
    Assert.AreEqual(3, result);
}
Sign up to request clarification or add additional context in comments.

3 Comments

This seems outside the scope of Roslyn, which is just code analysis
@Chris, actually Roslyn aims to provide full REPL / scripting capabilities, amongst other things. Check out some of the links.
Ok, cool. I feel like the scope of Roslyn keeps changing.
0

You can use CSharpCodeProvider to compile source code from a file or from strings into an assembly you can load. Then you can invoke the generated classes via reflexion.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.