Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an eval function In C#?

I'm typing an equation into a TextBox that will generate the graph of the given parabola. Is it possible to use an eval function? I'm using C# 2010 and it doesn't have Microsoft.JScript

like image 741
clay turner Avatar asked May 19 '11 00:05

clay turner


People also ask

Is there eval in C?

To evaluate a code in run time is only possible for interpreted languages, so you can't do that in a compiled language like C or C++.

What is eval function in C?

EVAL() evaluates Expression and returns the result of that expression. This function is useful when the expression to be evaluated is itself constructed by another expression. Contrast with the evaluate_template() function which executes Xbasic code that is stored in a variable.

Is eval a built in function?

Answer: eval is a built-in- function used in python, eval function parses the expression argument and evaluates it as a python expression. In simple words, the eval function evaluates the “String” like a python expression and returns the result as an integer.

Does C++ have an eval function?

Nope, your best bet is the command pattern. There are some C++ interpreters: stackoverflow.com/questions/69539/… -1 This is a terrible idea and I cannot in good conscience encourage it. If you get in the habit of solving problems with eval , you are getting in a very, very bad habit.


2 Answers

C# doesn't have a comparable Eval function but creating one is really easy:

public static double Evaluate(string expression)  
       {  
           System.Data.DataTable table = new System.Data.DataTable();  
           table.Columns.Add("expression", string.Empty.GetType(), expression);  
           System.Data.DataRow row = table.NewRow();  
           table.Rows.Add(row);  
           return double.Parse((string)row["expression"]);  
       }

Now simply call it like this:

Console.WriteLine(Evaluate("9 + 5"));
like image 84
Teoman Soygul Avatar answered Sep 19 '22 02:09

Teoman Soygul


You can easily do this with the "Compute" method of the DataTable class.

static Double Eval(String expression)
{
    System.Data.DataTable table = new System.Data.DataTable();
    return Convert.ToDouble(table.Compute(expression, String.Empty));
}

Pass a term in form of a string to the function in order to get the result.

Double result = Eval("7 * 6");
result = Eval("17 + 4");
...
like image 30
mar.k Avatar answered Sep 21 '22 02:09

mar.k