Evaluate numeric expressions that are entered by the user in C#


This example shows one way to evaluate mathematical expressions entered by the user at runtime.

Enter a numeric expression involving x and y in the upper text box. Then enter values for x and y in the lower text boxes and press the Evaluate button to make the program evalulate the expression.

The program executes the following code when you click the Evaluate button.

// Evaluate the expression.
private void btnEvaluate_Click(object sender, EventArgs e)
    // Turn the equation into a function.
    string function_text =
        "public static class Evaluator" +
        "{" +
        "    public static double Evaluate(double x, double y)" +
        "    {" +
        "        return " + txtExpression.Text + ";" +
        "    }" +

    // Compile the function.
    CodeDomProvider code_provider =

    // Generate a non-executable assembly in memory.
    CompilerParameters parameters = new CompilerParameters();
    parameters.GenerateInMemory = true;
    parameters.GenerateExecutable = false;

    // Compile the code.
    CompilerResults results =

    // If there are errors, display them.
    if (results.Errors.Count > 0)
        string msg = "Error compiling the expression.";
        foreach (CompilerError compiler_error in results.Errors)
            msg += "\n" + compiler_error.ErrorText;
        MessageBox.Show(msg, "Expression Error",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        // Get the Evaluator class type.
        Type evaluator_type =

        // Get a MethodInfo object describing the Evaluate method.
        MethodInfo method_info =

        // Make the parameter list.
        object[] method_params = new object[]

        // Execute the method.
        double expression_result = 
            (double)method_info.Invoke(null, method_params);

        // Display the returned result.
        txtResult.Text = expression_result.ToString();

The code first composes a class that includes a single function containing the expression entered by the user. The result looks something like this:

public static class Evaluator
    public static double Evaluate(double x, double y)
        return 2 * x + 4 * y + x * y;

The actual string has the class and its function all on one line of text. I’ve added line breaks here to make it more readable but the compiler doesn’t care.

Next the code creates a CodeDomProvider to compile C# code. It uses parameters to tell the provider to create a non-executable assembly built in memory, and then it calls the CompileAssemblyFromSource method to compile the Evaluator class with its Evaluate function.

If there are errors, the program displays them. Try adding some syntax errors to the equation to see what happens. If the error isn’t too extreme, the error messages are often good enough to let you fix the problem.

The code then gets a Type representing the Evaluator class and from that gets a MethodInfo object representing the class’s Evaluate method. The program makes a parameter array that holds the values of x and y to pass into the method and invokes the method, passing it those parameters. The program converts the method’s return result from a generic object into a double and displays it.

This method is not blindingly fast because it takes a little while to compile the Evaluator class. Once the class is compiled, however, calling it is fairly quick. That means you could evaluate the same function for many different values of x and y relatively quickly by compiling the class once and then invoking it many times.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in algorithms, mathematics, miscellany, programs, reflection and tagged , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Evaluate numeric expressions that are entered by the user in C#

  1. jay says:

    excellent!can u extend with expression from db table & store result to db table,also i want to add some custom class from c++ dll can i add?

  2. RodStephens says:

    You should be able to select text from a database and use this technique to execute it. Then you could save the result into the database.

    As for C++, the CodeDomProvider only knows about C#, JScript, and Visual Basic. I don’t think it can do C++. You used to be able to use Microsoft.VisualC.CppCodeProvider.CreateCompiler, but I think it is no longer supported.

    You might be able to use a third party tool. Or you could try to parse the equation yourself. Or if you can isolate just the equation, the C# provider might be able to evaluate it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.