In this article, we will see how we can use the power of DLR along with IronJS to evaluate expression at run time.
Introduction
Recently, while answering to a forum question of DNF, we thought of doing the same in a different way. After the advent of DLR followed by IronJS, we have the option of evaluating the dynamic expression.In this article we will address the approach to satisfy our needs
Environment Setup for IronJS
Let us create a Console Library Application and add IronJS from the Nuget Package Manager.Then let us write the below code
using System;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
// Instantiate the IronJS Engine
var context = new IronJS.Hosting.CSharp.Context();
string expression = string.Empty;
expression = "(((19+27)*1000)/((306-270)*7))";
//Execute method runs the dynamic code
object result = context.Execute(expression);
//print the result
Console.WriteLine(result);
Console.ReadKey();
}
}
}
/******** RESULT ******/
182.539682539683
/*********************/
The very first thing we need to perform is to instantiate the IronJS Engine which can be achieve by the below code
new IronJS.Hosting.CSharp.Context()
Next, we are assigning the expression.And finally we are executing the dynamic expression by using the Execute method of the IronJS Engine.
We can perform some more testing with our approach
CASE 1
Input: expression = "((10 + 12) * 5)";
Result: 110
CASE 2
Input: expression = "(((2+5)*1000)/((30-12)*6))";
Result: 64.8148148148148
CASE 3
Input: expression = "1*2*3*4*5*6*7*8*9";
Result: 362880
Reference
IronJS
Conclusion
In this article we have seen the how we can use the power of DLR along with IronJS to evaluate the expression at run time. Thanks for reading.Zipped file is attached herewith.