This post is part of a series about building a simple mathematical expression evaluator. For previous posts and full source code see Table of Contents.
Introduction In previous part we added support for variables but it has a big disadvantage: values of the variables are bound by position and not by name. This means that you should pass values for the variables in the same order as they appear in the expression. For example the following test will fail:

Introduction In part two of this series we built an expression evaluator capable of parsing expressions with parentheses. In this part we are going to add support for expression with variables.

Introduction In previous post I showed how to build a simple expression evaluator using expression trees. Although it works fine it has some drawbacks:
It does not support parentheses. It does not support variables. In some cases the result can be wrong as the parser is not using left to right parsing. It is compiling delegates for every expression which results in slower execution. To solve these issues we will use a different algorithm and deal with all points except variable support.

This is table of contents for Building Expression Evaluator with Expression Trees in C# series. We are going to build a simple mathematical expression evaluator in C# using expression trees. The library supports simple expressions such as 2.5+5.9, 17.89-2.47+7.16, 5/2/2+1.5*3+4.58, expressions with parentheses (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) and expressions with variables:
var a = 6; var b = 4.32m; var c = 24.15m; Assert.That(engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", a, b, c), Is.EqualTo((((9 - a / 2) * 2 - b) / 2 - a - 1) / (2 + c / (2 + 4)))); At the end of the series full source code will be available at github and the library will be published to NuGet.

© Giorgi Dalakishvili 2019 - 2024 · Powered by the Academic theme for Hugo.