# Mathematical Expression Evaluation with NCalc

Posted by in C# category on for Beginner level | Points: 250 | Views : 12423

NCalc is a mathematical expressions evaluator in .NET. NCalc can parse almost any mathematical expression and evaluate the result. In this article , we will look into the usage of NCalc with various examples.
Recommendation

## Introduction

NCalc is a mathematical expressions evaluator in .NET. NCalc can parse almost any mathematical expression and evaluate the result.In this article , we will look into the usage of NCalc with various examples.

## Using the code

Let us open a Console Application and then from the Nu-get Package Manager Console install NCalc as under

`PM> Install-Package ncalc`

Example 1: Arithmetical Expression Evaluation using NCalc

Let us look into the below program

```using NCalc;
using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{

#region Case 1: Arithmetical Expression Evaluation using NCalc

try
{

string expression = "((99*9) + (77+89)*20) / 45";
Expression e = new Expression(expression);
if (!e.HasErrors())
Console.WriteLine(e.Evaluate());
}
catch (EvaluationException e)
{
Console.WriteLine("Error catched: " + e.Message);
}

#endregion

}
}
}
```

NCalc is a set of assemblies that allows expressions evaluation. The heart of NCalc is the Expression class.This class has a method Evaluate() which returns the result.

The Expression class has four overloaded methods as under

```public Expression(LogicalExpression expression);
public Expression(string expression);
public Expression(LogicalExpression expression, EvaluateOptions options);
public Expression(string expression, EvaluateOptions options);
```

In the above example, first we are creating an instance of Expression using the overloaded constructor. This constructor takes a string as parameter. Then the method Evaluate() is invoked to parse the string and returns the actual value. The result is

`93.5777777777778`

The HasErrors() is use for determining the syntax errors before the expression evaluation.

NCalc Operators

Expressions can be combined using operators. Below is the list of operators that NCalc supports.

1. Primary
2. Unary
3. Bitwise
4. Multiplicative
6. Relational
7. Logical

Example 2: NCalc's Primary Operator Example

`Console.WriteLine(new Expression("99 * ( 90 + 9 )").Evaluate()); //Result : 9801`

Example 3: NCalc's Unary Operator Example

`Console.WriteLine(new Expression("not true").Evaluate()); //Result : False`

Example 4: NCalc's Bitwise Operator Example

```int a = 60;
int b = 14;

Console.WriteLine(new Expression( a +"&" +  b ).Evaluate()); //BITWISE AND (Result: 12)
Console.WriteLine(new Expression(a + "|" + b).Evaluate()); //BITWISE OR (Result: 62)
Console.WriteLine(new Expression(a + "^" + b).Evaluate()); //BITWISE XOR (Result: 50)
Console.WriteLine(new Expression(a + "<<" + 2).Evaluate()); //LEFT SHIFT (Result: 240)
Console.WriteLine(new Expression(a + ">>" + 2).Evaluate()); //RIGHT SHIFT (Result: 15)

```

Example 5: NCalc's Multiplicative Operator Example

`Console.WriteLine(new Expression("56 * 77 % 12").Evaluate()); //Result : 4`

Example 6: NCalc's Additive Operator Example

`Console.WriteLine(new Expression("100 + 200 - 567").Evaluate()); //Result : -267`

Example 7: NCalc's Relational Operator Example

```int x = 21;
int y = 10;

Console.WriteLine(new Expression(x + "==" + y).Evaluate()); //Result : False
Console.WriteLine(new Expression(x + "!=" + y).Evaluate()); //Result : True
Console.WriteLine(new Expression(x + "<" + y).Evaluate()); //Result : False
Console.WriteLine(new Expression(x + "<=" + y).Evaluate()); //Result : False
Console.WriteLine(new Expression(x + ">" + y).Evaluate()); //Result : True
Console.WriteLine(new Expression(x + ">=" + y).Evaluate()); //Result : True
Console.WriteLine(new Expression(x + "<>" + y).Evaluate()); //Result : True
```

Example 8: NCalc's Logical Operator Example

`Console.WriteLine(new Expression("true or false and true && true || false").Evaluate()); //Result : True`

Example 9: NCalc's Case sensitivity Example

By default, the evaluation process is case sensitive. This means every parameter and function evaluation will match using case.e.g.

```Console.WriteLine(new Expression("aBs(-18)").Evaluate());
```

This can be overcome if we use EvaluateOptions.IgnoreCase as shown below

`Console.WriteLine(new Expression("aBs(-18)",EvaluateOptions.IgnoreCase).Evaluate()); //Result : 18`

Example 10: NCalc's Conditional Expression Evaluation Example

`Console.WriteLine(new Expression("if(79 % 2 == 0, 'value is even', 'value is odd')").Evaluate()); //Result : value is odd`

Example 11: NCalc's Static parameters Example

Static parameters are values which can be defined before the evaluation of an expression.These parameters can be accesed using the Parameters dictionary of the Expression instance.

``` var exp = new Expression("2 * [x] ^ 2 + 24 * [y]");
exp.Parameters["x"] = 5;
exp.Parameters["y"] = 1;
Console.WriteLine(exp.Evaluate());  //Result : 16
```

Parameters can be useful when a value is unknown at compile time, or when performance is important and the parsing can be saved for further calculations.

Example 12: NCalc's Expression parameters Example

Expressions can be splitted into several ones by defining expression parameters. Those parameters are not simple values but Expression instances themselves. Let's look at the below example

```Expression totalSurfaceArea = new Expression("[area] * h");
Expression area = new Expression("[l] * [b]");
totalSurfaceArea.Parameters["area"] = area;
area.Parameters["l"] = 10;
area.Parameters["b"] = 20;
totalSurfaceArea.Parameters["h"] = 5;

Console.WriteLine(area.Evaluate());  //Result : 200
Console.WriteLine(totalSurfaceArea.Evaluate());  //Result : 1000
```

## References

State of the Art Expression Evaluation

## Conclusion

In this article, we have seen how powerful NCalc is and we can do multiple mathematical stuffs with this.Hope this will be helpful.Thanks for reading.Zipped file attached.

Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team

Login to vote for this post.