Basic Expression Tree Example
This example demonstrates how to create a simple expression like x => x + 2 dynamically.
using System; using System.Linq.Expressions; class Program { static void Main() { // Parameter: x ParameterExpression param = Expression.Parameter(typeof(int), "x"); // Constant: 2 ConstantExpression constant = Expression.Constant(2, typeof(int)); // Add operation: x + 2 BinaryExpression addExpression = Expression.Add(param, constant); // Lambda: x => x + 2 var lambda = Expression.Lambda<Func<int, int>>(addExpression, param); // Compile the lambda var compiledFunc = lambda.Compile(); // Invoke the lambda int result = compiledFunc(5); Console.WriteLine($"Result of x + 2 when x = 5: {result}"); // Output: 7 } }