How to Use NCalc for Dynamic Calculations and Formulas
What NCalc is
NCalc is a lightweight .NET expression-evaluator that parses and evaluates mathematical and logical expressions from strings. It supports parameters (static, expression-based, and dynamic), custom functions, caching, lambda compilation, async functions (via a separate package), and JSON serialization of parsed expressions.
Quick start (basic usage)
csharp
using NCalc; // evaluate a simple expression var expr = new Expression(“2 + 35”); var result = expr.Evaluate(); // 17
Parameters (static, expression, dynamic)
- Static:
csharp
var e = new Expression(“2 * [x] + [y]”); e.Parameters[“x”] = 5; e.Parameters[“y”] = 1; e.Evaluate();
- Expression parameters:
csharp
var vol = new Expression(”[surface] * h”); var surface = new Expression(”[l] * [L]”); vol.Parameters[“surface”] = surface; surface.Parameters[“l”] = 1; surface.Parameters[“L”] = 2; vol.Evaluate();
- Dynamic parameters:
csharp
var e = new Expression(“Round(Pow([Pi],2) + [X], 2)”); e.DynamicParameters[“Pi”] = _ => 3.14159; e.Parameters[“X”] = 10; e.Evaluate();
Custom functions
csharp
var e = new Expression(“Secret(3,6)”); e.EvaluateFunction += (name, args) => { if (name == “Secret”) args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate(); }; e.Evaluate(); // 9
Advanced features
- Lambda compilation (NCalc.LambdaCompilation) to convert expressions to delegates:
csharp
var expr = new Expression(“1 + 2”); Func<int> fn = expr.ToLambda<int>(); fn(); // 3
- Async support via NCalcAsync package for async functions/parameters.
- Caching: NCalc caches parsed expressions; you can control caching via options or plugins.
- JSON serialization (on .NET 8+) for parsed LogicalExpression objects.
Common options and patterns
- Use square brackets or curly braces for parameter names with special chars: [My Param] or {MyParam}.
- Use ExpressionOptions (e.g., NoCache, IgnoreCase, AllowNullParameter, IterateParameters).
- For repeated evaluations, predefine Parameters or compile to a lambda to improve performance.
Error handling and debugging
- Wrap Evaluate() in try/catch to capture parse/evaluation exceptions.
- For complex expressions, break into sub-expressions using Expression parameters to simplify debugging.
- Use EvaluateFunction/EvaluateParameter events to inspect/runtime-resolve values.
When to precompile
Precompile (ToLambda) or cache when the same parsed expression will be evaluated many times — compilation has upfront cost but greatly reduces per-evaluation time.
Useful links
- Official repo & docs: https://github.com/ncalc/ncalc and https://ncalc.github.io/ncalc
If you want, I can provide a small runnable sample project demonstrating dynamic parameters + custom functions and lambda compilation.
Leave a Reply