Access Employees

How to execute mathematical expressions in a string in .NET

Published in by Gustavo Mauricio de Barros

How to execute mathematical expressions in a string in .NET How to execute mathematical expressions in a string in .NET

🖩 What is NCalc

NCalc is a robust library for .NET that allows evaluating expressions defined as strings at runtime. Originally created by Sébastien Ros and currently maintained by me, it offers a powerful and extensible way to interpret and evaluate expressive logic with support for operators, parameters, conditional logic, and even custom functions!

Instead of writing rigid code for each business rule, you can empower your system to evaluate dynamic expressions created at runtime. This opens up a wide range of possibilities for rule engines, workflows, and any application that relies on configurable and flexible logic.

🧠 Detailed Architecture of NCalc

NCalc’s architecture is divided into three essential layers: parsing, expression execution, and the high-level interface represented by the Expression class. Each layer has a well-defined role, contributing to separation of concerns and extensibility.

🔍 Parsing

The parsing process transforms the expression string into a hierarchical data structure. NCalc uses Parlot as the parsing library, converting expressions like "1 + 2 * 3" into internal representations called ASTs (Abstract Syntax Trees).

You can also implement your own parser as long as it implements the ILogicalExpressionFactory interface, allowing you to adapt NCalc for very specific use cases or internal DSLs.

🌳 What is an AST?

AST stands for Abstract Syntax Tree. It’s a data structure that represents the grammar of the expression in a hierarchical manner. Instead of working with the raw string, the AST organizes operators and operands into nodes and subnodes.

For example, the expression "2 + 3 * 5" is not read from left to right, but rather as a tree where multiplication occurs before addition. The root node is the addition, and one of its children is a multiplication node. This structure allows NCalc to correctly evaluate complex expressions with precedence and associativity rules.

⚙️ Execution with Visitor Pattern

With the AST built, the next step is to execute the expression. This is done using the Visitor pattern, a classic design pattern that separates navigation logic from processing logic.

The visitor pattern works with polymorphism. A visitor has multiple methods for each class that can inherit from LogicalExpression, and this class has a method that accepts a visitor. You can dive deeper into this concept with this article by Sébastien Ros.

NCalc includes visitors like EvaluationVisitor and SerializationVisitor, and allows you to create your own.

This enables not just evaluation, but also transformation, optimization, serialization, or even validation of expressions prior to execution.

To define your own execution logic, simply implement the IEvaluationVisitorFactory interface.

🧪 Expression: The Main Class

The Expression class is NCalc’s main entry point. It handles all the magic for you: parsing, validation, and evaluation. Just instantiate it with a string and call Evaluate(). It also supports variable injection via dictionaries and custom functions.

You can build context-based calculation engines where expressions are loaded from databases, config files, or even typed in by end-users — all with safety and control.

The Expression class abstracts all the AST and Visitor Pattern logic from the library’s end users.

In addition, this class performs other important operations like AST caching and error detection.

💻 Examples

Simple evaluation:

Example 1

Custom functions:

Example 2

🚀 Why Execute Strings as Expressions?

Executing strings as expressions provides a major advantage: decoupling. Instead of hardcoding rules in C#, you can place them outside the application — and change them without recompiling. This is gold in systems that require agility and customization.

Common use cases include:

  • Rule engines (e.g., if age > 60 then discount = 20%)
  • Pricing and commission templates
  • Custom calculation logic defined by advanced users
  • Workflows with dynamic conditions
  • Configurable dashboards that calculate KPIs from formulas
  • Custom business rules like those in JJMasterData

📚 Additional Resources

← Return to start