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 a Static Lambda Still Capturing the Outer Instance

- 28.11.26 - ErcanOPAK

🔧 Fix a Static Lambda Still Capturing the Outer Instance

The static modifier on a lambda or local function only blocks the compiler from letting that specific lambda directly reference this or an instance member by name – it’s a syntactic rule enforced at the single lambda’s own body, not a guarantee about what any static member it’s still free to read might itself be holding. If one of those static members is a field that was populated earlier by an ordinary, non-static lambda that genuinely did capture this, then the static lambda reading that field ends up holding a reference to the very instance it was marked static specifically to avoid keeping alive – through a path the static-capture rule was never designed to see.

🔎 The Problem

public class ReportGenerator
{
    private readonly List<string> _log = new();

    // Cache populated once, elsewhere, by an instance method - this
    // static field now holds a delegate that captured 'this'
    private static Func<string, int>? _cachedScorer;

    public void RegisterScorer()
    {
        _cachedScorer = msg => _log.Count; // ordinary lambda, captures 'this' via _log
    }

    public Func<int, int> BuildPipeline()
    {
        return static x =>
        {
            // legal: _cachedScorer is a STATIC member, not an instance
            // member and not a captured local - referencing it satisfies
            // the 'static lambda captures nothing' rule completely
            var extra = _cachedScorer?.Invoke("tick") ?? 0;
            return x + extra;
        };
    }
}

// pipeline is a 'static' lambda, compiles cleanly, captures nothing from
// BuildPipeline's own scope - but if RegisterScorer() was ever called on
// some instance, _cachedScorer now holds a closure over THAT instance,
// and every call to pipeline() keeps that original instance reachable
// and alive for as long as the static field itself is never cleared,
// even though 'static' on the lambda promised exactly the opposite

✅ Fix: Audit What Static Fields Are Holding

  • Audit any static field or property a static lambda reads for whether its value could itself be a delegate, event handler, or object holding a captured instance – the static keyword on the lambda only guarantees that this lambda doesn’t capture anything new, not that every static member it touches is itself instance-free.
  • Clear or replace a cached delegate like _cachedScorer once the instance that registered it is disposed or goes out of scope, instead of leaving a static field holding a stale closure indefinitely – a static field’s lifetime is the application’s, so anything it captures lives exactly that long too.
  • Prefer a WeakReference, or a weak-event pattern, when a static cache genuinely needs to hold something tied to an instance’s lifetime, so the garbage collector can still reclaim the instance even if the code meant to clear the cache never ran.

🚨 Why This Is Dangerous

A static lambda reads as a strong, compiler-enforced promise that no instance is being kept alive through it, which makes a leak introduced this way almost invisible in code review – every rule a reviewer knows to check, no this, no captured locals, is satisfied by the lambda itself, while the actual leak sits one level removed, in whatever static field the lambda is still allowed to read.

static only promises that this closure captures nothing – it says nothing about what’s already sitting in the static state it’s still free to read.

— C# Best Practice

Related posts:

The Hidden Cost of async Without await in Real Applications

The Hidden Cost of async Without await in Real Applications

How to make the default class type 'public' instead of 'internal' in Visual Studio

How to make the default class type 'public' instead of 'internal' in Visual Studio

C# — Exceptions Are Extremely Expensive

C# — Exceptions Are Extremely Expensive

Views: 9
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

WordPress: Fix the Block Editor Autosave Dropping Custom Fields
The AI Prompt That Finds Which Test Assertion Is Flaky

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 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 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# 868 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 @ 631 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 562 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