65.9K
CodeProject is changing. Read more.
Home

String Parser and Evaluator

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (20 votes)

Apr 8, 2003

viewsIcon

109734

downloadIcon

2919

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] + [B]/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.