🔧 C#: Fix an Expression Tree Compiling Once Then Caching Stale Data
Compiling an Expression<Func<T, bool>> with .Compile() is deliberately expensive, so it’s common to cache the resulting delegate keyed by some identifier for reuse. If that expression tree closes over a captured variable — a filter value read from configuration, say — rather than taking it as a parameter, the compiled delegate bakes in whatever that variable’s value was at compile time, and every cached call after that silently keeps using the original value even after the source configuration changes.
🔎 The Problem
int minAge = _config.GetValue<int>("MinAge"); // e.g. 18
Expression<Func<Person, bool>> expr = p => p.Age >= minAge;
var compiled = expr.Compile();
_cache["adultFilter"] = compiled;
// _config.MinAge later changes to 21 at runtime
// _cache["adultFilter"] still checks >= 18 forever -
// the captured 'minAge' was baked in, not re-read
✅ Fix: Parameterize What Can Change, Cache Only What Can’t
- Build the expression to take the variable value as an actual lambda parameter, e.g.
(Person p, int minAge) => p.Age >= minAge, and pass the current value in at call time instead of capturing it from an outer scope at compile time. - If the filter genuinely needs to react to configuration changes, invalidate and recompile the cached delegate whenever the source value changes, rather than assuming a one-time compile step is safe to reuse indefinitely.
- Cache compiled delegates keyed by the actual captured value when there are only a few distinct values in practice (a small set of thresholds, for instance), so each distinct value gets its own correctly-compiled delegate instead of one delegate silently serving all of them incorrectly.
🚨 Why This Is Dangerous
- A business rule that was correctly updated in configuration — a new age limit, a changed price threshold — can keep silently applying the old value everywhere the compiled expression was cached, with no error and no log entry indicating the configuration change didn’t actually take effect.
Compiling an expression freezes more than just its logic — it freezes every captured value right along with it, whether you meant to or not.



