Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
C#

C#: Fix an Expression Tree Compiling Once Then Caching Stale Data

- 27.11.26 - ErcanOPAK

🔧 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.

— C# Best Practice

Related posts:

C#: Use Span for High-Performance Memory Access Without Allocation

C#: Use Span for High-Performance Memory Access Without Allocation

C#: Use Static Local Functions to Prevent Variable Capture

C#: Use Static Local Functions to Prevent Variable Capture

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

C#: Async/Await Best Practices to Avoid Deadlocks and Performance Issues

Views: 9
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

The AI Prompt That Finds Which Dependency Bump Broke a Build
SQL Server: Fix a Temporal Table History Missing a Dropped Column

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 996 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 995 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 866 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 629 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 561 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com