0

Okay, I know that in Python, say you had a string called

strExpression and it's value was "1+2-(3*5)"

There is a python method (function, sorry I get the terms confused) that will evaluate that string and return a numerical integer value (in this case, it should return -12. I don't recall the python syntax because I did it a while ago in a course (and then I broke my arm and had to quit because I couldn't type), but hopefully someone knows what I mean

Is there a way to do this in C#

I am only learning, and am creating a simple calculator program, and I have made a basic one that allows you to add to the previous number, but I would like to extend it a bit for my own benefit. Thank you very much for any help.

Luke
  • 1
  • Duplicate question: http://stackoverflow.com/questions/333737/c-evaluating-string-342-yield-int-18 – Peter Dec 08 '10 at 07:30
  • possible duplicate of [How can I evaluate a C# expression dynamically?](http://stackoverflow.com/questions/53844/how-can-i-evaluate-a-c-sharp-expression-dynamically) – t0mm13b Jul 05 '12 at 14:09

3 Answers3

1

There isn't exactly such a method in C#, but you can easily write one using the compiler at runtime to evaluate the expression. Check out CSharpCodeProvider.

jason
  • 236,483
  • 35
  • 423
  • 525
1

You can use the Microsoft.JScript which exposes all client side javascript functions in C#

using System;
using Microsoft.JScript;
using Microsoft.JScript.Vsa;

namespace JustTest
{
    class Program
    {
        static void Main(string[] args)
        {
            object value = Eval.JScriptEvaluate("1+2-(3*5)", VsaEngine.CreateEngine());
            Console.Write(value);
            Console.ReadLine();
        }
    }
}
dhinesh
  • 4,676
  • 2
  • 26
  • 44
0

Try this it uses CodeDOM to create a calculator

Conrad Frix
  • 51,984
  • 12
  • 96
  • 155