Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Eval() support [duplicate]

Tags:

we need to evaluate a value in an object in run time while we have a textual statement of the exact member path for example: myobject.firstMember.secondMember[3].text
we thought of parsing this textual statement using regex and then evaluate the text value by using reflection but before we do that i wonder if C# support some kind of eval ability? so we won't have to do the parsing ourself. How do microsoft do this in their immediate window or watch windows?

thanks you very much,

Adi Barda

like image 599
Adi Barda Avatar asked Jun 21 '09 14:06

Adi Barda


2 Answers

Probably the easiest way is to use DataBinder.Eval from System.Web.UI:

var foo = new Foo() { Bar = new Bar() { Value = "Value" } }; var value = DataBinder.Eval(foo, "Bar.Value"); 
like image 114
Alex Yakunin Avatar answered Oct 09 '22 12:10

Alex Yakunin


I have written an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into Expression Trees without using compilation or reflection.

You can write something like:

var interpreter = new Interpreter(); var result = interpreter.Eval("8 / 2 + 2"); 

or

var interpreter = new Interpreter()                 .SetVariable("service", new ServiceExample());  string expression = "x > 4 ? service.SomeMethod() : service.AnotherMethod()";  Lambda parsedExpression = interpreter.Parse(expression,                          new Parameter("x", typeof(int)));  parsedExpression.Invoke(5); 

My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .

like image 33
Davide Icardi Avatar answered Oct 09 '22 12:10

Davide Icardi