Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .NET 4.0 expression eval [duplicate]

Possible Duplicates:
C# eval equivalent?
How can I evaluate a C# expression dynamically?

How can I evaluate a valid C# code and get results inside a compiled program (dynamically)? I know this is not very clear, i'll try to show that with a code snippet:

Visual C# 2010.

double x = 3.0;//this is function argument, we'll take 3
string str = "Math.Pow(x,2)+2*x+4";//value with written function in C#,equals: x^2+2x+4
double y = eval(str);
/* this is the idea! something like JS.I want to make string parsed into parameter,i.e
y=19 - this is what double y should became after eval(str) */

Hope you got the idea.

Thanks.

like image 730
Vladislav Bolshakov Avatar asked Nov 19 '25 06:11

Vladislav Bolshakov


1 Answers

No, LINQ won't do this for you.

The closest you can easily get at the moment is to use CSharpCodeProvider which allows you to compile a whole assembly - but you'll need to wrap your expression in all the other source code required to make it a complete class.

like image 118
Jon Skeet Avatar answered Nov 21 '25 19:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!