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

Community
  • 1
  • 1
Behrouz Ghazi
  • 399
  • 2
  • 7
  • 23
  • I doubt that would be possible since the string wouldn't get parsed until after the program has been compiled – Ayush Jan 20 '12 at 16:49
  • @xbonez: It's possible to emit your own IL and execute it so I would say it's most definitely possible. – Austin Salonen Jan 20 '12 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. – driis Jan 20 '12 at 16:56

2 Answers2

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);
}
driis
  • 161,458
  • 45
  • 265
  • 341
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.

Falanwe
  • 4,636
  • 22
  • 37