Visual C# Developer Center > Visual C# Forums > Visual C# General > Validate an arithmetic expression programatically in c#?
Ask a questionAsk a question
 

AnswerValidate an arithmetic expression programatically in c#?

  • Tuesday, April 29, 2008 6:57 AMml_coro Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

     

    validate input like:

     

     2+1-(3*2)+8/2

     

    and return its answer using MDAS rule

     

    //returns 1

Answers

  • Tuesday, April 29, 2008 11:39 AMtimvw Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Apart from a couple of expression evaluators:

    http://www.codeplex.com/Flee

    http://www.codeplex.com/LazyParser

    You could also create a DataTable, add a DataColumn and exploit it's Expression property Wink

    Code Snippet

    string expression = "2+1-(3*2)+8/2";

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("col1", typeof(int), expression);
    dataTable.Rows.Add(new object[] { });
    Console.WriteLine(dataTable.Rows[0][0]);






All Replies

  • Tuesday, April 29, 2008 7:20 AMSandeep Aparajit Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    Dear  ml_coro,

     

    The answer that is returned (1) is correct using the Bracktes, MDAS rules. You can verify it in

    http://www.google.co.in/search?hl=en&q=2%2B1-%283*2%29%2B8%2F2&meta=

  • Tuesday, April 29, 2008 8:22 AMLasse V. Karlsen Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    If you want to validate a string containing "2+1-(3*2)+8/2" in C#, you're either going to have to write a math expression parser/evaluator, or use the CodeDom support to compile the code to C# (with its syntax restrictions) and call the code directly.
  • Tuesday, April 29, 2008 11:39 AMtimvw Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Apart from a couple of expression evaluators:

    http://www.codeplex.com/Flee

    http://www.codeplex.com/LazyParser

    You could also create a DataTable, add a DataColumn and exploit it's Expression property Wink

    Code Snippet

    string expression = "2+1-(3*2)+8/2";

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("col1", typeof(int), expression);
    dataTable.Rows.Add(new object[] { });
    Console.WriteLine(dataTable.Rows[0][0]);






  • Wednesday, April 30, 2008 5:11 AMml_coro Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
     timvw wrote:
    Apart from a couple of expression evaluators:

    http://www.codeplex.com/Flee

    http://www.codeplex.com/LazyParser

    You could also create a DataTable, add a DataColumn and exploit it's Expression property Wink

    Code Snippet

    string expression = "2+1-(3*2)+8/2";

    DataTable dataTable = new DataTable();
    dataTable.Columns.Add("col1", typeof(int), expression);
    dataTable.Rows.Add(new object[] { });
    Console.WriteLine(dataTable.Rows[0][0]);






     

    is there a way to do this programatically?

    actually, your code really worked...

  • Wednesday, April 30, 2008 7:36 AMSoe Moe Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    Hi ml_coro,

           hope, this article can help you..

     

    http://www.codeproject.com/KB/cpp/rpnexpressionevaluator.aspx?display=Print

     

    regards,

    soe moe

     

  • Wednesday, April 30, 2008 10:41 AMMatthew Watson Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     

    If you want to get really silly about this, you could use the C# compiler to dynamically compile the expression and evaluate it. Smile

     

    Here is an example way to do this; you should be able to see how you could extend this to work with other kinds of expressions. It's well over-the-top and probably grossly inefficient - but I think it could be extremely powerful:

     

    Code Snippet

    using System;
    using System.Reflection;
    using System.CodeDom.Compiler;

     

    using Microsoft.CSharp;


    class Program
    {
        static void Main(string[] args)
        {
            TestExpression("2+1-(3*2)+8/2");
            TestExpression("1*2*3*4*5*6");
            TestExpression("Invalid expression");
        }

     

        static void TestExpression(string expression)
        {
            try
            {
                int result = EvaluateExpression(expression);
                Console.WriteLine("'" + expression + "' = " + result);
            }

     

            catch (Exception)
            {
                Console.WriteLine("Expression is invalid: '" + expression + "'");
            }
        }

     

        public static int EvaluateExpression(string expression)
        {
            string code = string.Format  // Note: Use "{{" to denote a single "{"
            (
                "public static class Func{{ public static int func(){{ return {0};}}}}",
                expression
            );

     

            CompilerResults compilerResults = CompileScript(code);

     

            if (compilerResults.Errors.HasErrors)
            {
                throw new InvalidOperationException("Expression has a syntax error.");
            }

     

            Assembly assembly = compilerResults.CompiledAssembly;
            MethodInfo method = assembly.GetType("Func").GetMethod("func");

     

            return (int)method.Invoke(null, null);
        }

     

        public static CompilerResults CompileScript(string source)
        {
            CompilerParameters parms = new CompilerParameters();

     

            parms.GenerateExecutable = false;
            parms.GenerateInMemory = true;
            parms.IncludeDebugInformation = false;

     

            CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp");

            return compiler.CompileAssemblyFromSource(parms, source);
        }
    }