Home > Posts > Evaluate Expression in .Net with Eval Function

The Evaluator class generates the required code block from a simple expression and executes it to give the same functionality of an Eval function in a scripting language.



Download Evaluator.cs (Right Click->Save Target As...).

Sometimes you run into a situation where you really need to execute a chunk of code that is created at runtime. An example of this might be allowing users to define rule expressions at runtime and saving them for later evaluation.

It has a built in caching mechanism to significantly cut down on the number of generated assemblie loaded into memory. It supports variables in the expression further allowing expressions to be reused. It supports either VB.Net or C# syntax. It even allows custom functions to be called from within the expression.

Evaluator eval = new Evaluator(
	"first = Multiply(first, second)",
	Evaluator.EvaluationType.SingleLineReturn,
	Evaluator.Language.CSharp);

eval.AddVariable("first", 5, typeof(int));
eval.AddVariable("second", 2, typeof(int));

eval.AddCustomMethod(@"
	public static int Multiply(int value1, int value2)
	{
		return value1 * value2;
	}");

Evaluator.EvaluationResult result = eval.Eval();

if (result.ThrewException)
{
	Console.WriteLine("Exception:");
	Console.WriteLine(result.Exception);
	Console.WriteLine();
	Console.WriteLine(result.GeneratedClassCode);
}
else
{
	if (result.Result != null)
	{
		Console.WriteLine(result.Result.ToString());
	}

	foreach (string variableName in result.Variables.Keys)
	{
		Console.WriteLine(variableName + ": " + result.Variables[variableName].VariableValue.ToString());
	}

	Console.WriteLine();
	Console.WriteLine(result.GeneratedClassCode);
}
Please send any questions or comments to Bruce Dunwiddie.