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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With