Evaluate an expression at runtime using IronJS

Rajnilari2015
Posted by in .NET Framework category on for Beginner level | Points: 250 | Views : 654 red flag

In this article, we will see how we can use the power of DLR along with IronJS to evaluate expression at run time.


 Download source code for Evaluate an expression at runtime using IronJS

Recommendation
Read Calculator Application Using IronJS and WPF before this article.

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.

Page copy protected against web site content infringement by Copyscape

About the Author

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


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)