Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / C#
Article

Yet Another Expression Evaluator

Rate me:
Please Sign up or sign in to vote.
4.17/5 (3 votes)
24 Jul 20052 min read 39.1K   16   7
An expression evaluator in C#.

Image 1

Introduction

It was one of the articles on Expression Evaluator that got me thinking, how easy it was to write an expression evaluator in C# with different types. Well thinking is one thing and doing another. So I set about to write an expression evaluator, which could take in data of types long, double, string and boolean.

I am still at learning C#, so I decided to experiment a bit with all kinds of programming constructs. In places where a foreach could have been very useful, I have used a while. Pardon me for this indulgence.

The classes

public class ExpressionEvaluator

Fields

C#
// the tokens of the converted postfix expression 
protected string[] postfix
// the list of operators         
protected string[] operators
// the list of seprarators       
protected string[] separators 
// operator precedence table     
protected Hashtable precedence
// My own stack only for strings     
protected StringStack stack
// Symbol table for identifiers        
protected Hashtable symbol_table
// infix the tokens of the input infix expression  
protected string[]

Constructors

C#
public ExpressionEvaluator(string exp)
public ExpressionEvaluator(string exp, 
                     ref Hashtable sym) : this(exp)

The first constructor receives a string infix expression. It populates the operator precedence table and converts the infix expression to a postfix expression. The second constructor, receives a reference symbol table from the user of the class. Whenever an identifier is found in the expression, the value is either read or updated in the symbol table.

Public methods

C#
public string Solve()

The user of the class, calls this method to solve the expression. Basically this implements the postfix expression evaluation algorithm.

Protected methods

C#
protected string Evaluate(string opr, 
          string operand1, string operand2)

This method, gets the types operand object from the string, checks if the operation opr is valid for the types of operand1 and operand2. If valid it calls the GetResult() method, else throws an InvalidTypeConversionException exception.

C#
protected void InfixToPostfix()

Converts the infix[] tokens to postfix[] token list.

C#
protected bool IsOperator(string str)

Checks if str is an operator.

C#
protected string GetResult(string opr, 
                   object obj1, object obj2)

This function actually applies opr to the objects obj1 and obj2. It returns the result as string.

C#
protected bool IsValidTypeConversion(TypeCode t1, TypeCode t2)

Checks if the type conversion is a valid one.

C#
protected object GetTypedOperand(string operand)

Given a string operand, it returns a typed object. Here I tried to use some regular expressions to identify the typed object to return. If none of the regular expression patterns match, we assume it is an identifier. Here is the source snippet:

C#
string long_pattern = "([0-9])+";

string double_pattern = "(?:[0-9]*\\.)?[0-9]+";

string string_pattern = 
   "\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"";

string bool_pattern = "(true|false)+";

if (Regex.IsMatch(operand, long_pattern))

    return Int64.Parse(operand);

if (Regex.IsMatch(operand, double_pattern))

    return Double.Parse(operand);

if (Regex.IsMatch(operand, string_pattern))

    return operand.Substring(1,operand.Length-2);

if (Regex.IsMatch(operand.ToLower(), bool_pattern))

    return Boolean.Parse(operand);

return null;

public class MalformedExpException : Exception

When a postfix expression cannot be parsed on the stack, the exception is thrown.

public class InvalidIdentifierException : Exception

When a token in an expression is an identifier, and cannot be found in the symbol table, the exception is thrown.

public class InvalidTypeConversionException : Exception

When a type conversion is invalid, the exception is thrown

public class InvalidOperationOnType : Exception

When an operation cannot be applied to types of operands, the exception is thrown.

Improvements

  1. I would like to implement operations like string + long.

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


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReference to stack Pin
Keerni11-Sep-06 0:31
Keerni11-Sep-06 0:31 
Generala few additional things Pin
wickerman.2625-Jul-05 8:57
wickerman.2625-Jul-05 8:57 
GeneralRe: a few additional things Pin
Jitesh Patil25-Jul-05 18:55
Jitesh Patil25-Jul-05 18:55 
GeneralProject is incomplete Pin
wickerman.2625-Jul-05 8:00
wickerman.2625-Jul-05 8:00 
GeneralRe: Project is incomplete Pin
Jitesh Patil25-Jul-05 18:53
Jitesh Patil25-Jul-05 18:53 
GeneralDownload link is invalid Pin
kenan3424-Jul-05 21:48
kenan3424-Jul-05 21:48 
GeneralRe: Download link is invalid Pin
Jitesh Patil25-Jul-05 1:34
Jitesh Patil25-Jul-05 1:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.