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
Try this
Demo
You can compile code from string at runtime and execute it:
Regular Expression evaluation can be done using
DataTable.Compute
method (from MSDN) :Try this:
Simply try this
I don't know, Why you want more complex? It's very easy ..
And if you want surely that,You can do that by using
EvaluateExpression
........................
See this discussions
Evaluating string "3*(4+2)" yield int 18
Update:
If those values came from input textbox, then write this way
And also you can find out some pretty answer from this discussion
Is it possible to compile and execute new code at runtime in .NET?
Update 2:
Finally I have tried this sample for you :
My full code for class library