Expression Trees & Dynamic Compilation

Advanced Updated November 16, 2024

🌲 6. Expression Trees and Dynamic Compilation

Expression trees allow you to represent code as data, used in LINQ providers like Entity Framework.

🔸 Creating an Expression Tree

Expression<Func<int, int>> square = x => x * x;
var compiled = square.Compile();
Console.WriteLine(compiled(5));  // Output: 25

🔸 Building Expressions Dynamically

ParameterExpression param = Expression.Parameter(typeof(int), "x");
var body = Expression.Multiply(param, param);
var lambda = Expression.Lambda<Func<int, int>>(body, param);