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
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"));
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");
...
using System.Data
must be included and an assembly reference must be added for System.Data
. –
Gordan 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();
}
}
string a=MyComplexThings(); System.Windows.Forms.MessageBox.Show(a)
–
Rip It's possible using the System.Reflection.Emit or System.CodeDom namespaces, but it's not exactly a good idea as there's no mechanism to control what namespaces are and are not allowed to be used. You write an eval() expecting simple expressions, and the next thing you know a user is suing you because your code allowed them to enter a string that wiped their hard drive. eval()
-like functions are huge gaping security holes and should be avoided.
The preferred alternative in the .Net world is a DSL (domain specific language). If you google around, you can find some pre-created DSL's for common tasks such as arithmetic.
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");
Can we do it like this.
var a = Console.ReadLine(); // give string here, ex: "1 + 2"
double result = Convert.ToDouble(new System.Data.DataTable().Compute(a, null));
But i fear, C# DataTable compute do not support Exponent Operator (** or ^).
- Example: "2^3" -> throws an error.
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.
© 2022 - 2024 — McMap. All rights reserved.