Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

C# RPN Expression

3.31/5 (5 votes)
31 Mar 2009CPOL1 min read 31.9K   564  
Calculate expressions with variables and functions using RPN.

Introduction

This article describes a simple but powerful expression parser using RPN. Expressions know how to deal with variables and functions. Additional functions can also be implemented.

Background

The calculations are based on RPN - Reverse Polish Notation. Read more about RPN here: http://www.calculator.org/rpn.html.

Using the code

The usage is very simple. Just create an environment and an expression, supply the expression string and variables, and calculate.

The environment is used to register the functions. Sometimes, functions are not needed so there so no need to register them.

C#
ExprEnvironment environment = new ExprEnvironment();
RPNFunctionUtils.RegisterFunctions(environment);

RPNExpr expr = new RPNExpr();
expr.Environment = environment;
expr.AddVariable(new Variable("X", 4));
expr.AddVariable(new Variable("Y", 5));
expr.Prepare();
label5.Text = expr.GetValue().ToString();

Once an expression is prepared, you may call GetValue many times with different variables. The expression will just go through the stack and calculate the value rather than parse the whole expression again.

C#
expr.VariableByName("X").value = 9;
expr.VariableByName("Y").value = 3;
label5.Text = expr.GetValue().ToString();

The RPN stack can be extracted from the list and shown to the user.

Points of interest

Try to implement your own function. It's very easy, you can find an example in the demo. Data fields can also be implemented. If you use something like [MyField] in an expression string, the expression will call the environment to return the value. You need to inherit the environment and you are ready to use the expression with data fields.

History and thanks

I should mention that RPNExpression was first written in Delphi and then rewritten to C# with some help from my friends Gregor Jakša and Matjaž Oman.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)