// using System.Linq.Expressions; var person = new Person { Name = "John", Age = 30 }; ParameterExpression paramExpr = Expression.Parameter(typeof(Person), "p"); MemberExpression memberExpr = Expression.Property(paramExpr, "Name"); Funcfunc = Expression.Lambda >(memberExpr, paramExpr).Compile(); string name = func(person); Console.WriteLine(name); // output: John
// using System.Linq.Expressions; // create a ParameterExpression ParameterExpression paramExpr = Expression.Parameter(typeof(int), "x"); // create a BinaryExpression that adds 2 to the parameter x BinaryExpression addExpr = Expression.Add(paramExpr, Expression.Constant(2)); // create a LambdaExpression that takes an int x and returns x + 2 ExpressionIn this example, an Expression tree is used to create a dynamic function that adds 2 to an integer value. The code creates a ParameterExpression for the integer value, a BinaryExpression that adds 2 to the parameter, and a LambdaExpression that takes an integer value and returns the sum. Finally, the LambdaExpression is compiled into a Func delegate that can be called with an integer value to get the sum. Package library: System.Linq.Expressions.> lambdaExpr = Expression.Lambda >(addExpr, paramExpr); // compile the LambdaExpression into a Func delegate Func addFunc = lambdaExpr.Compile(); // call the dynamic function with a value of 3 int result = addFunc(3); // output: 5