0Pricing
C# Academy · Lesson

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)); // 6

Compiling 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)); // 12

All lessons in this course

  1. What Are Expression Trees
  2. Building Expressions Manually
  3. Compiling and Executing Expressions
  4. Expression Trees in LINQ Providers
← Back to C# Academy