Click here to Skip to main content
15,893,814 members
Articles / Programming Languages / C#

Runtime C# Expression Evaluator

Rate me:
Please Sign up or sign in to vote.
4.83/5 (71 votes)
20 Apr 2002Ms-PL1 min read 273.5K   4K   97  
A C# class (and library if needed) to do runtime evaluations of C# expressions
using System;
using ADOGuy;

namespace TestEvaluator
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Test
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
      Console.WriteLine("Test0: {0}", Evaluator.EvaluateToInteger("(30 + 4) * 2"));
      Console.WriteLine("Test1: {0}", Evaluator.EvaluateToString("\"Hello \" + \"There\""));
      Console.WriteLine("Test2: {0}", Evaluator.EvaluateToBool("30 == 40"));
      Console.WriteLine("Test3: {0}", Evaluator.EvaluateToObject("new DataSet()"));

      EvaluatorItem[] items = {
                                new EvaluatorItem(typeof(int), "(30 + 4) * 2", "GetNumber"),
                                new EvaluatorItem(typeof(string), "\"Hello \" + \"There\"", "GetString"),
                                new EvaluatorItem(typeof(bool), "30 == 40", "GetBool"),
                                new EvaluatorItem(typeof(object), "new DataSet()", "GetDataSet")
                              };
      
      Evaluator eval = new Evaluator(items);
      Console.WriteLine("TestStatic0: {0}", eval.EvaluateInt("GetNumber"));
      Console.WriteLine("TestStatic1: {0}", eval.EvaluateString("GetString"));
      Console.WriteLine("TestStatic2: {0}", eval.EvaluateBool("GetBool"));
      Console.WriteLine("TestStatic3: {0}", eval.Evaluate("GetDataSet"));
    }
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions