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 Mi
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"));
Thank you so much Mr.Teoman Soygul
if you want to catch the error then you can use try catch,then we can use that values to future purpose.
try
{
DataTable table = new System.Data.DataTable();
table.Columns.Add("expression", string.Empty.GetType(), expression);
DataRow row = table.NewRow();
table.Rows.Add(row);
return double.Parse((string)row["expression"]);
}
catch (Exception)
{
return -1;
}
I created the ExpressionEvaluatorCs Nuget package inspired by mar.k's answer and also added the option to specify return type.
Sample code
// Returns object 6
object result1 = ExpressionEvaluator.Evaluate("(1 + 2) * 2");
// Returns int 6
int result1 = ExpressionEvaluator.Evaluate<int>("(1 + 2) * 2");
You can create one yourself by using CodeDom. It will be slow because it creates a new assembly every time you call Eval.
public class Program
{
static void Main(string[] args)
{
Console.WriteLine(ExpressionEvaluator.Eval("(2 + 2) * 2"));
}
}
public class ExpressionEvaluator
{
public static double Eval(string expression)
{
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
CompilerResults results =
codeProvider
.CompileAssemblyFromSource(new CompilerParameters(), new string[]
{
string.Format(@"
namespace MyAssembly
{{
public class Evaluator
{{
public double Eval()
{{
return {0};
}}
}}
}}
",expression)
});
Assembly assembly = results.CompiledAssembly;
dynamic evaluator =
Activator.CreateInstance(assembly.GetType("MyAssembly.Evaluator"));
return evaluator.Eval();
}
}
There is no native C# eval function; but as others have previously stated, there are several workarounds for what you are trying to do.
If you're interested in evaluating more complicated C# code, my C# eval program provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, http://csharp-eval.com, for additional details.
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");
...