Compiling and Executing Expressions
Turn expression trees into runnable delegates.
From Tree to Delegate
An expression tree is data until you compile it. Expression<TDelegate>.Compile() turns the tree into a real delegate you can invoke.
using System;
using System.Linq.Expressions;
Expression<Func<int, int>> tree = x => x + 1;
Func<int, int> fn = tree.Compile();
Console.WriteLine(fn(5)); // 6Compiling a Hand-Built Tree
Trees you build manually compile the same way, producing a working delegate.
using System;
using System.Linq.Expressions;
var x = Expression.Parameter(typeof(int), "x");
var body = Expression.Multiply(x, Expression.Constant(3));
var lambda = Expression.Lambda<Func<int, int>>(body, x);
var fn = lambda.Compile();
Console.WriteLine(fn(4)); // 12All lessons in this course
- What Are Expression Trees
- Building Expressions Manually
- Compiling and Executing Expressions
- Expression Trees in LINQ Providers