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.

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular