String calculator

GM-Xile GM-Xile picture GM-Xile GM-Xile · Feb 22, 2014 · Viewed 24.8k times · Source

Hi fellow programmers,

I am creating a calculator in C#

and I have a string variable math which contains 100 * 5 - 2

How can I display its output which is 498 in my console?

My code is this:

String math = "100 * 5 - 2"; 

Console.WriteLine(math);

Console.ReadLine(); // For Pause

So basically, what my code will give me is the string itself which 100 * 5 - 2

but I want it to give me 498 as a result.

Idea about this is pretty much appreciated.

Thanks

Answer

Sudhakar Tillapudi picture Sudhakar Tillapudi · Feb 22, 2014

Regular Expression evaluation can be done using DataTable.Compute method (from MSDN) :

Computes the given expression on the current rows that pass the filter criteria.

Try this:

using System.Data;//import this namespace

 string math = "100 * 5 - 2";
 string value = new DataTable().Compute(math, null).ToString();