Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 182 ยท Standard Library

Expression Trees and Dynamic

Learn C# expression trees: Expression<Func<>>, building and compiling code at run time, visiting trees, plus dynamic, ExpandoObject and the DLR.

Most code is a recipe the compiler turns into instructions. An expression tree is different: it is a recipe stored as data. Instead of a compiled method, you get an object tree that says "multiply the parameter x by 2, then add 1", which a program can read, change, translate to another language (such as SQL) or compile into a fast delegate at run time.

The second half of this lesson covers the opposite approach: dynamic, where the compiler stops checking and the lookup of members happens while the program runs. Both features are about code that is decided at run time, both are easy to misuse, and both have a clear job. After this lesson you will know what an Expression<Func<T>> is, how to build and compile one, how to walk a tree with a visitor, and when dynamic or ExpandoObject fit. You should know lambdas, delegates and the basics of reflection.

A lambda as data

When you assign a lambda to a Func<int, int>, the compiler produces a normal method. When you assign the same lambda to an Expression<Func<int, int>>, the compiler instead produces code that builds a tree of objects describing the lambda. You can then look inside.

C# Lambda as code versus lambda as data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The tree for x * 2 + 1 has an Add node at the top. Its left child is a Multiply node (with the parameter x and the constant 2), and its right child is the constant 1. Every node is an object derived from System.Linq.Expressions.Expression, and the classes are immutable: to change a tree, you build a new one.

Only simple expression lambdas can become trees. A lambda with a statement body (curly braces and return), an assignment, await or the null-propagating operator ?. cannot be converted to Expression<...>; the compiler reports an error.

Why would you want this?

The best-known use is LINQ to databases. When you write db.Products.Where(p => p.Price > 10) against Entity Framework Core, the lambda is passed as an Expression<Func<Product, bool>>, not as a delegate. EF reads the tree and translates it to WHERE Price > 10 in SQL. A plain delegate is an opaque compiled method that EF could only run in memory. This is the difference between IEnumerable<T> (takes delegates) and IQueryable<T> (takes expression trees), which you met in LINQ basics.

Other uses:

  • Strongly typed member names without strings: Property(x => x.Name) yields the name "Name", and the compiler checks it.
  • Fast reflection: build and compile a getter once, then call it like a normal method.
  • Rules engines and dynamic filters: combine conditions chosen by a user into one predicate.
  • Mappers and serializers that generate specialized code per type.

Reading names from expressions

This is the most common beginner-friendly use: ask for a lambda instead of a string, and extract the member name.

C# Strongly typed property names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Careful: for u => u.Age where the property is an int, the expression body is sometimes wrapped in a conversion node (Convert) when the lambda's return type is object. Here the generic TProp keeps the exact type, so no wrapper appears. The built-in nameof(User.Email) operator covers many of these cases without any tree at all; expression-based names are for APIs that need to accept a selector.

Building trees by hand

You do not have to write a lambda: you can create nodes with factory methods such as Expression.Parameter, Expression.Constant, Expression.Add, Expression.Call and Expression.Lambda. This is how you build code whose shape is not known at compile time, for instance a filter built from user input.

C# Building and compiling an expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Compile() turns the tree into IL and returns a delegate. This takes real time (the first compile in a process is especially slow, often several milliseconds), so compile once and keep the delegate; compiling inside a loop is a classic performance bug. After compiling, the delegate runs about as fast as a normal lambda. That is why serializers and mappers like to generate property accessors this way.

On platforms that cannot generate code at run time (Native AOT, some mobile and WebAssembly targets), Compile() falls back to a slow interpreter or is unavailable. Check your target before depending on it.

Combining predicates

A realistic example is building a search filter from optional criteria. You want one Func<Product, bool>, assembled from only the conditions the user actually filled in.

C# A dynamic filter from optional criteria

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two ideas matter here. First, each lambda has its own parameter object; AndAlso(left.Body, right.Body) would refer to two different parameters and fail when compiled ("variable 'p' of type ... referenced from scope '', but it is not defined"). The fix is to rewrite the right body so it uses the left parameter. Second, that rewrite is done by an expression visitor.

Visiting trees

ExpressionVisitor is a base class that walks a tree and lets you override VisitXxx methods for the node kinds you care about; everything else is copied unchanged (trees are immutable, so a visitor returns new nodes). Visitors are how LINQ providers translate trees to SQL, and how tools optimize or rewrite them.

C# A visitor that explains a tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The explainer prints nodes in the order the visitor meets them: first the outer AndAlso, then the Equal comparison on its left, then Modulo inside it, then the leaves n, 2 and 0, and only then the right-hand side n > 10. That is a depth-first walk, left to right. Each override either returns the node as it is or returns a replacement. The folder shows rewriting: the tree x => (x * (2 + 3)) becomes x => (x * 5), and the compiled delegate returns 20 for 4. (If you write x * (2 + 3) in an ordinary lambda, the C# compiler already folds 2 + 3 to 5 for you, which is why we built this tree by hand.)

dynamic: skipping compile-time checks

Now the other side. The type dynamic tells the compiler "do not check members of this value; figure it out at run time". Operations on a dynamic value are bound when the line runs, by the Dynamic Language Runtime (DLR), a layer of .NET that finds the right member, caches the lookup and also powers interop with Python- or JavaScript-style objects.

C# dynamic basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice what is missing: IntelliSense, refactoring and compile-time errors. Misspell ToUpper and the program compiles, then fails with a RuntimeBinderException. Everything that touches a dynamic value also returns dynamic, so the lack of checking spreads through the code like a stain. Do not confuse dynamic with var (a normal static type, inferred by the compiler) or object (a static type that needs casts).

Genuine uses of dynamic are narrow:

  • COM interop (Excel, Word automation) and other late-bound APIs.
  • Interop with dynamic languages, such as IronPython.
  • Quick scripts and tests that poke at loosely structured data.
  • Library tricks like calling the right overload for the runtime type (a poor man's double dispatch). A switch on type patterns is usually better.

ExpandoObject: an object that grows

System.Dynamic.ExpandoObject is a bag of properties you can add and remove while the program runs. Used through dynamic, it looks like a normal object; used through IDictionary<string, object?>, it is a dictionary.

C# ExpandoObject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

ExpandoObject is handy for building JSON-like structures, for configuration scraps and for tests. For anything with a known shape, define a record or class instead; you get typo protection, documentation and speed for free. If you only need a dictionary of unknown keys, Dictionary<string, object?> is clearer than ExpandoObject.

DynamicObject: your own dynamic behavior

When you derive from System.Dynamic.DynamicObject, you decide what happens when someone reads, writes or calls a member that does not exist. That is how wrappers are built that expose JSON, XML or a database row as if it had real properties.

C# A DynamicObject that wraps a dictionary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Returning true means "I handled it"; returning false makes the runtime throw its usual binder exception. Wrapper objects like this are elegant to call, but they cost speed (every access goes through the binder machinery) and give up all tooling, so keep them for small, well-documented seams.

Choosing between the tools

Need Best fit
Pass a condition to a database provider Expression<Func<T, bool>> (that is what IQueryable uses)
Get a member name type-safely nameof, or an Expression<Func<T, TProp>> selector
Call a member found by name, once or twice Reflection
Call a member found by name, millions of times Compile an expression (or delegate) once and cache it
Generate code with no run-time cost A source generator (see source generators)
Talk to COM or a dynamic language dynamic
Hold loosely structured, short-lived data Dictionary<string, object?>, JsonNode or ExpandoObject
Anything with a known shape A normal class or record

Common mistakes

  • Compiling a tree on every call. Cache the delegate (a static field or a dictionary).
  • Passing a delegate where a tree is needed. IQueryable.Where takes an Expression<Func<...>>; if you store the predicate in a Func<...> variable first, the LINQ provider receives a plain delegate and loads everything into memory before filtering.
  • Expecting statement lambdas in a tree. Only expression-bodied lambdas convert.
  • Mixing parameters between two lambdas when combining them (see the filter example).
  • Using dynamic to avoid defining a type. You trade the compiler's help for a little typing.
  • Forgetting that dynamic is contagious. One dynamic value makes the whole expression dynamic; convert back to a static type as soon as you can with a cast.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the difference between Func<int, int> f = x => x + 1 and Expression<Func<int, int>> e = x => x + 1?

    The first is executable code. The second is a tree of objects that can be inspected, rewritten and, with Compile(), turned into a delegate.
  2. 2. Why does Entity Framework's Where method take Expression<Func<T, bool>>?

    A delegate is opaque compiled code. A tree can be walked and translated into SQL so the database does the filtering.
  3. 3. What does Compile() on an expression tree return?

    Compile generates IL and returns a delegate of the lambda's type (for example Func<int, int>). It is a relatively costly operation, so cache the result.
  4. 4. What happens when you use dynamic value.NoSuchMember on a List<int>?

    With dynamic the compiler does not check members. The runtime binder looks the member up while the program runs and throws RuntimeBinderException when it cannot find it.
  5. 5. Which is the best choice for an object whose properties are fixed and known at compile time?

    A normal type gives compile-time checking, tooling and speed. Dynamic types only make sense when the shape is unknown until run time.

Summary

  • An Expression<TDelegate> is a lambda stored as an immutable tree of Expression nodes; it can be inspected, rewritten and compiled.
  • LINQ providers such as Entity Framework read expression trees (IQueryable) to translate conditions to SQL; IEnumerable uses plain delegates.
  • Build trees with Expression.Parameter, Constant, Add, Call, Lambda and friends; call Compile() once and cache the delegate.
  • ExpressionVisitor walks and rewrites trees, for example to combine predicates that have different parameters.
  • dynamic moves member lookup to run time through the DLR: useful for COM and dynamic languages, risky elsewhere.
  • ExpandoObject and DynamicObject create objects whose members are decided at run time; prefer records and classes when the shape is known.

Next: Dependency Injection