Middle · Trace · Expression trees are data and delegates execute

Predict the inspected node kinds and both arithmetic results.

Think through your answer before opening the explanation.

Runtime & concurrency

using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;

Expression<Func<int, int>> tree = value => value * 2 + 1;
Func<int, int> direct = value => value * 2 + 1;
var body = (BinaryExpression)tree.Body;
Console.WriteLine($"node:{body.NodeType}");
Console.WriteLine($"left:{body.Left.NodeType}");
Console.WriteLine($"interpreted:{tree.Compile(preferInterpretation: true)(3)}");
Console.WriteLine($"delegate:{direct(3)}");
Reveal answer and reasoning

The lines are node:Add, left:Multiply, interpreted:7, and delegate:7. The tree represents value multiplied by two, with one then added, so its outer BinaryExpression is Add and its left operand is another binary multiplication. Supplying three gives six plus one. The directly declared delegate has the same bounded formula and returns the same numeric answer for that input.

The program requests actual local interpretation through the public Compile overload; it does not contact a database or inspect native instructions. The common wrong trace reports Multiply as the root because it overlooks the later addition, or treats the tree as inert data that can never be executed. These lines establish structure and one expected result, not identical performance between representations.

Different inputs, overflow policies, captured dependencies, or a restricted translation provider require additional contracts and tests beyond this small arithmetic observation.

What a strong answer covers

  • The root is Add and its left is Multiply.
  • Both paths return seven for three.
  • The output contains no benchmark or provider result.

Common pitfall

Confusing arithmetic precedence with the outermost expression-tree node.

Follow-up questions

  1. What changes if the final constant becomes three?
  2. How would a checked arithmetic expression affect node kinds?

Self-review

Choose what to revisit. These marks are your own assessment and are separate from lesson completion.

Primary references

Open lesson and code ↗

← All interview questions