Compiler-Cached Lambdas Break a No-Static-State Test
A rule against static state takes ten lines of test code to enforce, but the test sees compiler output, not the source I read, and the C# compiler creates static fields whenever I write a lambda that captures no variables.
1-minute summary
- Symptom / problem
- A no-static-fields test keeps failing even though nobody wrote the word static.
- Who should read
- C# developers enforcing a no-static-state rule with a reflection test.
- Fix in short
- The cause is non-capturing lambdas, whose delegates the compiler caches in a generated static field. Write them in a form that is not cached, and add companion tests to catch it.
I have a desktop app written in C# where I set a rule from day one: no mutable static fields, enforced by a test rather than memory. A few days later, the build was green, but this test failed. The fields it reported had strange names that nobody had typed, and grepping for static in the reported file found nothing. This happened 5 times in one week, with a different author each time. So I wrote down what caused it and why I chose to fix the code instead of the test.
I have replaced all namespace and class names in this article with generic names, but the code patterns, test failure messages, and numbers are real.
Why ban static in the first place?
This app has several threads running concurrently: the UI thread, a shared memory watcher, a file tailer, a scheduler, and an audio player. Later, it also needs to run multiple instances of the app's model in one process, one per destination. Even one piece of static state would be shared unintentionally by all instances, and that kind of bug would not show up when running just one instance.
I did not want this rule to live in documentation, because nobody reads documentation when they are in a hurry. The rule lives in this test.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
public class ArchitectureTests
{
[Theory]
[InlineData("App.Shm")] // ไลบรารี shared memory
[InlineData("App.Layout")] // ไลบรารี layout
[InlineData("App.Ui")] // ตัว UI
public void No_mutable_static_fields_anywhere(string assemblyName)
{
Assembly asm = Assembly.Load(assemblyName);
var offenders = new List<string>();
const BindingFlags flags = BindingFlags.Static | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
foreach (System.Type t in asm.GetTypes())
foreach (FieldInfo f in t.GetFields(flags))
if (!f.IsInitOnly && !f.IsLiteral) // ไม่ readonly และไม่ใช่ const
offenders.Add(t.FullName + "." + f.Name);
Assert.True(offenders.Count == 0, string.Join("\n", offenders));
}
}
IsInitOnly identifies fields declared readonly, while IsLiteral identifies const fields and enum members, which are also literal static fields at the metadata level. Those two categories pass. Everything else is writable static state and counts as a violation. The test runs against 3 assemblies, and GetTypes() returns every type, including compiler-generated nested types. That is where this story starts.
The symptom: field names nobody wrote
The failure message looked like this.
$ dotnet test --filter No_mutable_static_fields_anywhere
Failed No_mutable_static_fields_anywhere(assemblyName: "App.Ui")
Error Message:
App.Ui.OverlayPanel+<>c.<>9__7_0
Expected: True
Actual: False
The + indicates a nested type. Names such as <>c and <>9__7_0 cannot be written directly in C# source because they contain <>.
My first guess was wrong. I thought someone had accidentally added a real static field and that the strange names were just how reflection displayed it. So I grepped for static throughout that assembly's folder. I found no fields, only methods and const declarations, which the test was not reporting anyway. My second guess was that the test was counting fields from an external library bundled into the assembly. That was wrong too, because the type name at the front was clearly one of my own classes.
The reported class contained only this code.
using System.Collections.Generic;
namespace App.Ui;
public sealed class Row
{
public long T;
public string Text = "";
}
public sealed class OverlayPanel
{
private readonly List<Row> _items = new();
public void Add(Row r)
{
_items.Add(r);
_items.Sort((a, b) => a.T.CompareTo(b.T)); // บรรทัดนี้คือตัวที่ถูกฟ้อง
}
}
There was no static keyword anywhere, but there was one lambda. That lambda used no outside variables, only its own parameters, a and b.
The cause: non-capturing lambdas are cached in static fields
A lambda that captures nothing behaves the same each time it is created, so the C# compiler does not create a new delegate every time execution reaches that line. It creates a hidden class named <>c inside the type, with a single instance stored in a static readonly field named <>9, then caches each delegate in another static field named <>9__N_M. This latter field is not readonly because it is first assigned when execution reaches the code, not when the type is loaded.
Written back into C#, the compiler's output would look roughly like this.
// สิ่งที่คอมไพเลอร์สร้างให้ เขียนกลับเป็น C# ให้อ่านง่าย
// ชื่อจริงมีเครื่องหมาย <> ซึ่งเขียนเองในซอร์สไม่ได้ ผมแทนด้วย __c, __9 ให้อ่านออก
[CompilerGenerated]
private sealed class __c // ชื่อจริง <>c
{
public static readonly __c __9 = new __c(); // <>9 readonly
public static Comparison<Row>? __9__7_0; // <>9__7_0 เขียนได้
internal int Add_b__7_0(Row a, Row b) => a.T.CompareTo(b.T);
}
public void Add(Row r)
{
_items.Add(r);
_items.Sort(__c.__9__7_0 ??= new Comparison<Row>(__c.__9.Add_b__7_0));
}
The __9__7_0 field is public static and not readonly, so it matches the test's !f.IsInitOnly && !f.IsLiteral condition exactly. The test is not wrong. It is reporting what actually exists in the assembly.
Lambdas that capture variables do not trigger this, because capturing a local variable makes the compiler create a new closure object per call. The delegate is bound to that object, leaving nothing to cache statically. That led to a counterintuitive situation: the "cleaner" lambda, which touches no outside state, is the one that makes the no-static test fail.
Which patterns trigger it, and which do not?
After the second occurrence, I checked each pattern by building it and letting the same test report the result. This is the table I got with the compiler the project uses.
| Source pattern | What the compiler does | Writable static field |
|---|---|---|
(a, b) => a.T.CompareTo(b.T) with no captures |
Caches the delegate in <>c |
Yes |
static (a, b) => ... with the static keyword before the lambda |
Exactly the same as the row above | Yes |
x => x.T > limit where limit is a local variable |
New closure object per call | No |
x => x.T > _limit using only a field on this |
Method on the class itself, with a new delegate each time | No |
items.Sort(CompareByTime) where the method is static |
Newer compilers cache it in another hidden class | Yes |
items.Sort(CompareByTime) where the method is an instance method |
Creates a new delegate each time | No |
rows.Where(r => r.Text != "").OrderBy(r => r.T) |
Each lambda is cached separately | Yes |
Two rows are commonly misunderstood.
The static keyword before a lambda has one job: make the compiler report an error if I accidentally capture a variable or this. It does not change how the delegate is cached. This kind of lambda still ends up in the same static field. Replacing a lambda with a method group is not an automatic solution either. If the target method is static, newer C# compilers also cache the method group's delegate in a static field. Build it and let the test decide with the compiler actually in use. Do not rely on reading the source.
The 5 actual occurrences were a List.Sort call taking a lambda in the overlay layer, a Func field initialised with a lambda, a Sort call in the host, two lambdas in the registration parser, and OrderBy and Where LINQ calls in a feature added later. Each had a different author, and each built without warnings, because the compiler saw nothing wrong.
<>cContains a static cache->Reflection testSees a writable field->FailureUnreadable field nameTwo options, and the one I did not choose
The first option is to teach the test to ignore compiler-generated members. It is easy: add one condition.
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
static class GeneratedFilter
{
// ทางที่ผมไม่ได้ใช้: ข้าม type ที่คอมไพเลอร์สร้าง และ field ที่ชื่อขึ้นต้นด้วย <
public static bool IsCompilerNoise(Type t, FieldInfo f) =>
t.IsDefined(typeof(CompilerGeneratedAttribute), inherit: false) ||
f.Name.StartsWith("<", StringComparison.Ordinal);
}
The second option is to write the code in all three assemblies without any non-capturing lambdas, leaving every character of the test unchanged.
Exempt compiler-generated members
- One fix, with no changes to application code
- Write lambdas and LINQ as usual
- The test has an exception to remember and maintain
- Names starting with < also cover backing fields for static auto-properties, so the condition must be narrow enough
Avoid non-capturing lambdas
- The test has no exceptions and can be trusted at a glance
- A comparer is a named class that can be found and tested separately
- The code gets slightly longer wherever a lambda used to be
- New contributors will always hit an initial test failure, so the failure message needs an explanation
I chose the second option. Performance was not the reason. A cached delegate is not application state and does not cause multiple instances to interfere with each other. Looking only at risk, the first option is safe enough. But I wanted this test to read as one sentence: "No writable statics. That's it." Once there is one exception, the next person who hits a failure will ask whether their case qualifies, and the exception list will keep growing. Choosing the first option is fine with me. Just make a clear decision and document the reason in the test, rather than patching things up each time it fails.
The replacements I use
Every lambda was replaced with one of these four patterns.
using System;
using System.Collections.Generic;
namespace App.Ui;
// 1) comparer เป็นคลาสจริง สร้างครั้งเดียวเก็บใน field ของ instance
public sealed class ByTime : IComparer<Row>
{
public int Compare(Row? a, Row? b) => a!.T.CompareTo(b!.T);
}
public sealed class OverlayPanelFixed
{
private readonly List<Row> _items = new();
private readonly ByTime _byTime = new();
// 2) hook แบบ nullable ให้คนเรียกใส่เอง แทน Func field ที่ initialise ด้วย lambda
public Func<Row, bool>? Filter;
public void Add(Row r)
{
if (!Pass(r)) return;
_items.Add(r);
_items.Sort(_byTime); // ไม่มี delegate ไม่มีอะไรให้แคช
}
private bool Pass(Row r) => Filter == null || Filter(r);
// 3) เรียงด้วย key แยก ไม่ต้องมี comparer เลย
public Row[] SortedCopy()
{
Row[] rows = _items.ToArray();
long[] keys = new long[rows.Length];
for (int i = 0; i < rows.Length; i++) keys[i] = rows[i].T;
Array.Sort(keys, rows); // เรียง rows ตามลำดับของ keys
return rows;
}
// 4) ลูป for แทน LINQ สั้น ๆ
public int CountWithText()
{
int n = 0;
for (int i = 0; i < _items.Count; i++)
if (_items[i].Text.Length > 0) n++;
return n;
}
}
I use Array.Sort(keys, items) more often than I expected. It sorts two arrays together by the values in the first array, without a delegate or an extra comparer class. It works well for sorting by a single numeric value. The nullable hook replaces a Func field whose initial value was a lambda. Its initial value becomes null, and a regular method takes over the decision.
I put the steps for handling this test failure directly in its failure message, so someone encountering it for the first time does not have to grep through the code as I did.
- Read the type name before the
+. That is the class containing the lambda, not a class containing an explicit static field. - If the field name contains
<>9__, look for lambdas or LINQ in that class that use no outside variables. - Replace them with a comparer class,
Array.Sort(keys, items), a nullable hook, or aforloop. - If the field has a human-written name, it is a real static field. Move it to an instance field and pass it through the constructor.
- Build and rerun the same test. Do not draw conclusions just from reading the source, because the test checks compiler output.
The same test catches real problems too
If this test caught only lambdas, I would have removed it. But that same week, it also caught a real static field: a counter declared static for generating sequence numbers. When multiple instances of the app's model ran in one process, they all drew numbers from the same counter, so each instance's numbers were no longer consecutive and could not be compared across instances. This bug cannot show up when running just one instance, and it is exactly why the rule exists.
Reflection sees everything in the assembly, including compiler-generated types. The upside is that indirect code cannot evade the rule. The downside is that a rule conceived at the source level may not match what is actually checked. Before adopting a test like this, try three or four ordinary code patterns and see what the test sees.
Two companion tests
The same file contains two other architecture tests based on the same idea: turn assumptions the code relies on into tests.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
public class EnvironmentTests
{
// struct ของ shared memory สมมุติว่า pointer กว้าง 8 ไบต์
[Fact]
public void Process_is_x64()
{
Assert.Equal(Architecture.X64, RuntimeInformation.ProcessArchitecture);
Assert.Equal(8, IntPtr.Size);
}
// ห้ามมีชื่อ kernel object ของระบบรุ่นเก่าหลงอยู่ในซอร์ส
[Fact]
public void No_legacy_object_names_in_source()
{
// ประกอบจากชิ้นย่อย ไม่งั้นไฟล์เทสต์นี้จะ match ตัวเอง
string banned = "Legacy" + "Bus" + "_Ready";
string root = Path.Combine(AppContext.BaseDirectory, "src");
foreach (string path in Directory.EnumerateFiles(root, "*.*", SearchOption.AllDirectories))
{
byte[] raw = File.ReadAllBytes(path);
string asLatin1 = Encoding.Latin1.GetString(raw); // ไฟล์ทั่วไป
string asUtf16 = Encoding.Unicode.GetString(raw); // ไฟล์สคริปต์ที่เก็บเป็น UTF-16
bool hit = asLatin1.Contains(banned, StringComparison.Ordinal) ||
asUtf16.Contains(banned, StringComparison.Ordinal);
Assert.False(hit, path);
}
}
}
The first requires an x64 process because the struct layout in shared memory assumes a particular pointer size. If someone runs it on another architecture one day, I want a test failure rather than incorrect values being read at runtime. The second scans the source for names that should no longer exist. Two details came from mistakes. First, the forbidden string must be assembled from smaller pieces; otherwise, the test file itself contains that string and the test always fails. Second, files must be read as both Latin-1 and UTF-16, because scripts in some languages are stored as UTF-16. Reading only as single-byte text leaves a zero byte between every character, and the search finds nothing.
To sum up, tests that enforce architectural rules are worth their cost, but I need to know what they can see. Non-capturing lambdas, static lambdas, static method groups, and LINQ all leave static fields in the assembly even when the source does not contain the word static. Exempting them and banning them outright are both valid choices, but do not leave teammates staring at <>9__7_0 and guessing what it means. If I have missed anything in the explanation, or a future compiler changes its behaviour, I will come back and update this.
Hit something like this? Stuck somewhere?
Come trade notes on the LinuxThai board



Comments 0
No comments yet — be the first