Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate a user-entered string in C#? [duplicate]

Tags:

c#

I am trying to build a calculator in C#. Now I would like to know whether it is possible to do a calculation, which is inside a textfield. For example a user enters into a textfield (2*3)+6. Now how would I tell my script to calculate this and then output the result?

like image 457
Chris Avatar asked Dec 09 '22 01:12

Chris


2 Answers

You could 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 don't expect to be able to calculate any complex functions with this method. You are limited to basic arithmetic.

And if you wanted to handle more complex expressions you could use CodeDOM.

like image 177
Darin Dimitrov Avatar answered Dec 11 '22 14:12

Darin Dimitrov


You can use the System.Linq.Dynamic library to do 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 of it here.

N.B. the string could've just been "(2 * 3) + 6", but this method has the bonus that you can pass in values to the equation too.

like image 21
markmuetz Avatar answered Dec 11 '22 14:12

markmuetz