How to calculate user input string in c #?

I am trying to build a calculator in C #. Now I would like to know if it is possible to make a calculation that is inside the text box. For example, the user enters a text field (2*3)+6 . Now, how can I tell my script to calculate this and then output the result?

+4
source share
2 answers

You can use the Compute method:

 using System; using System.Data; class Program { static void Main() { var result = new DataTable().Compute("(2*3)+6", null); Console.WriteLine(result); } } 

prints:

 12 

Of course, you cannot count on any complex functions using this method. You are limited to basic arithmetic .

And if you want to handle more complex expressions, you can use CodeDOM .

+13
source

You can use the System.Linq.Dynamic library for this:

`

  static void Main(string[] args) { const string exp = "(A*B) + C"; var p0 = Expression.Parameter(typeof(int), "A"); var p1 = Expression.Parameter(typeof(int), "B"); var p2 = Expression.Parameter(typeof(int), "C"); var e = System.Linq.Dynamic.DynamicExpression.ParseLambda(new[] { p0, p1, p2 }, typeof(int), exp); var result = e.Compile().DynamicInvoke(2, 3, 6); Console.WriteLine(result); Console.ReadKey(); } 

`

You can download a copy here .

NB line could only be "(2 * 3) + 6", but this method has a bonus that you can pass in the values ​​for the equation too.

+1
source

Source: https://habr.com/ru/post/1402549/


All Articles