devxlogo

Evaluate an expression at runtime

Evaluate an expression at runtime

The .NET framework doesn’t offer any direct way to evaluate an expression that has been entered by the end user when the application is running. However, it is quite simple to create a simple expression evaluator based on calculated columns in DataTable. The following routine does the trick:

Function EvalExpression(ByVal expr As String) As Double    ' create a new DataTable containing a calculated column    Dim dt As New DataTable()    dt.Columns.Add("Expr", GetType(Double), expr)    ' add a dummy row    dt.Rows.Add(dt.NewRow)    ' return the value of the calculated column    Return CDbl(dt.Rows(0).Item("Expr"))End Function

Here’s an example that uses the above function:

Dim expr As String = "100 * (2 + 3)"Console.WriteLine(EvalExpression(expr))   ' displays 500

You can also support variables by creating one or more column named after the variables, as in this function:

Function EvalExpression(ByVal expr As String, ByVal x As Double) As Double    ' create a new DataTable     Dim dt As New DataTable()    ' first, add a column named after the variable    dt.Columns.Add("x", GetType(Double))    ' then add the calculated column    dt.Columns.Add("Expr", GetType(Double), expr)    ' add a dummy row    dt.Rows.Add(dt.NewRow)    ' set the value of the variable    dt.Rows(0).Item("x") = x    ' return the value of the calculated column    Return CDbl(dt.Rows(0).Item("Expr"))End Function

You can use the overloaded version of the function as follows:

Dim expr As String = "x*x + 3*x + 4"Dim res As Double = EvalExpression(expr, 10)

Notice that the operation of creating the DataTable and its dummy row is rather time-consuming. If you plan to reuse the same expression with different values for different values of the variable you should create the DataTable only once and reuse it for all subsequent evaluations.

The expression parser built in the DataSet and DataTable objects supports all the usual math and comparison operators, except the ^ operator. You can use the % symbol in place of the MOD operator, and the + symbol for string concatenations. The LIKE operator is similar to the T-SQL and VB6 operator with same name. A few functions are supported as well: IIF, LEN, ISNULL, CONVERT, and SUBSTRING. For more information see the SDK documentation.

See also  5 Tips for Working With an Onsite Interpreter
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist