NCalc – Mathematical Expressions Evaluator for .NET
troii does Java and .NET Software development and Consulting. We like both „worlds“ but in our opinion, one of the main drawbacks of .NET, compared to Java, is the lack of good OpenSource frameworks and projects. There are so many projects that start and after a few months they fall asleep.
In this post we’d like to tell you about a really great OpenSource .NET project called NCalc.
Last month I needed an attributed grammar for custom mathematical evaluations and started some web research to find existing projects. I came up with COCO /R and ANTLR. Both are free parser generators and can be used for C++, Java and C#. Even if COCO /R is from the University of Linz, not far away from us, I decided to use ANTLR due to the more powerful community behind it.
What we needed was a mathematical expression evaluator which calculates dynamic expressions like (2 + 5) * 3
. Another requirement to the grammar was that it had to support functions like GetValue("objectName", "valueName")
which does a query to get a value from an proprietary object cloud. So we needed something that evaluates an expression like GetValue("car", "throttle") * 3
.
I was already designing the grammar when I found this article on CodeProject. It describes and solves exactly what I was looking for. The article is excellent and it seems that the author, Sebastien Ros, decided to provide the complete solution now as NCalc on CodePlex.
NCalc is extremly flexibly. It allows us to use functions and parameters out of the box. E.g. if we have to use a lot of GetValue("car", "throttle")
functions we can create a parameter to substitute this function with a parameter. Now we can use the throttle value much easier in our expressions by (THROTTLE * 3) + (THROTTLE * 2)
.