C# Eval - My First Evaluation - Evaluate a C# expression with a return type

CSharp · Console

/Program.cs

// C# Eval Expression
// Doc: https://eval-expression.net/my-first-evaluation

// @nuget: Z.Expressions.Eval

/*
## Evaluate a C# expression with a return type

In the last two examples, we learned how to execute code dynamically and use variables in our expressions.

The last remaining part is how to specify a return type. If no return type is specified, the value is of type `object`.

The `Execute<TReturn>` method takes as the generic type the type to return.

In this example, we will continue with our getting started example by using our `list` and `greaterThan` variables but this time, specify the `List<int>` return type.

Did you spot an error in this example? The expression should return an `IEnumerable<int>` and not a `List<int>`! However, our library is smart enough and makes your life easy by automatically calling the `ToList` method to return the right type. That is one of the many advantages of using our library.

See more: https://eval-expression.net/my-first-evaluation
*/

using System;
using System.Dynamic;
using System.Collections.Generic;
using Z.Expressions;

public class Program
{
	public static void Main()
	{
		var list = new List<int>() { 1, 2, 3, 4 };
		var greaterThan = 2;

		list = Eval.Execute<List<int>>("list.Where(x => x > greaterThan)", new { list, greaterThan });
		
		FiddleHelper.WriteTable(list);
	}
}
;