Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Evaluate an expression at runtime

Total Hit ( 2414)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


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:

Click here to copy the following block
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:

Click here to copy the following block
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:

Click here to copy the following block
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


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.