4

Duplicate of: How can I evaluate a C# expression dynamically?

See also: C# eval equivalent?

How to evaluate expression. Maybe like:

int a=1;
int b=3;
int c=Eval("a+b");

or

int c=int.parse("1+3*(2+3)");

This seems stupid to me. is it possible in c#?

Community
  • 1
  • 1
ebattulga
  • 10,774
  • 20
  • 78
  • 116

3 Answers3

7

You can take code, and using the CSharpCodeProvider write an Eval function that actually compiles your code into an in-memory assembly and then executes that code.

See this CodeProject article for sample source.

joshperry
  • 41,167
  • 16
  • 88
  • 103
  • This works, but it produces a new assembly, so while you can use it to eval logical statements, you can't use it for metaprogramming. This is coming in C#5 (see anders's PDC2008 talk on the future of C#) – Orion Edwards Feb 11 '09 at 00:48
2

Not directly. C# contains no runtime compiler. There is an open source project attached to Mono that will do this.

Shog9
  • 156,901
  • 35
  • 231
  • 235
thinkbeforecoding
  • 6,668
  • 1
  • 29
  • 31
0

I enumerate several different approaches that I am aware of in this answer to "How can I evaluate a C# expression dynamically" which include various .NET framework solutions such as CodeDomProvider, DataBinder.Eval, DataTable.Compute, Document.InvokeScript, and more.

cdiggins
  • 17,602
  • 7
  • 105
  • 102