Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

String Parser and Evaluator

0.00/5 (No votes)
7 Apr 2003 1  
Formula parser for C#

Sample Image - String_Evaluator.gif

Introduction

This formula evaluator can use different data types like int, double, string, DateTime or bool to calculate the value of a mathematical expression. You can use any of the operators, +, -, *, /, >, <, == etc., and specify parameters for them.

Background

.NET doesn't support types like Variant as in VB6 or Delphi. To avoid validating data type before doing any operation, I could create Variant type that can be used to save data of different types and overload some operators that are frequently used, like bitwise +, unary + -, *,/.

This code works in 2 steps: First, parse the expression and transform it to Backward Poland Notation. Now every order item can be either an operator or an operand. Second, calculate value of order using stack. Variables are saved in a public static field, that has the Hashtable type shown in the "string/value" view.

Using the code

To use this code, you must add a reference to the Evaluator.dll library.

Hashtable ht = new Hashtable();
ht.Add("A",12);
ht.Add("B",15);
Za.Evaluator.Evaluator.Variables = ht;
try
{
    textBox1.Text = Za.Evaluator.Evaluator.Evaluate("[A] + /1.2").ToString();
}
catch(Za.Evaluator.CalcException ex)
{
    SomeCode xxxxxxxxx;
}
catch(Exception ex)
{
    SomeCode xxxxxxxxx;
}            

To realize addition functions, you need to edit EmbeddedFunction in Calculator.cs file.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here