CodeBlanks Logo Icon CodeBlanks

Expression.Compile

C# course · Advanced · Lesson 40/83

Learn to build delegates at runtime with Expression.Compile.

Expression.Compile

Compile() turns an expression tree into a runnable delegate at runtime. With var fn = expr.Compile(); you get a Func<T> that you can call like fn(5).

The conversion emits IL at runtime and wraps it in a delegate; this has an up-front cost, but subsequent calls are fast. It is a key tool for dynamic code generation, rule engines and expression-based query providers.

When to use Compile?

Compile is used when you build an expression tree at runtime. For example, if you combine conditions from user input into a filter, you compile the result into a delegate and run it over data.

Rule engines and dynamic query systems are typical users. If the expression tree is known at compile time, you don't need Compile — the Expression<T> can already be a delegate.

Exercise Build a delegate with Compile and invoke it

Define an expression tree with Expression<Func<int, int>> square = x => x * x;. Build a delegate with Func<int, int> fn = square.Compile();. Print fn(5) with Console.WriteLine.

Show example solution
Define the expression tree with Expression<Func<int, int>> square = x => x * x;. Build the delegate with Func<int, int> fn = square.Compile();. Print with Console.WriteLine(fn(5));.
Example solution:
using System;
using System.Linq.Expressions;

class Program
{
    static void Main()
    {
        Expression<Func<int, int>> square = x => x * x;
        Func<int, int> fn = square.Compile();
        Console.WriteLine(fn(5));
    }
}

Test yourself

  1. Complete the Compile call

    var fn = expr.____();
    Show answer
    var fn = expr.Compile();
  2. What does Compile return?

    • An expression tree
    • A string
    • A Type object
    • A runnable delegate
    Show answer

    A runnable delegate — Correct. Compile returns a runnable delegate.

  3. Match the method to its purpose

    Compile
    Produces a delegate
    Invoke
    Calls the delegate
    NodeType
    Gives the operation kind
    Parameters
    Gives the parameter list

All lessons in Advanced