C# - Can I use a [ThreadStatic] field with a static local function to avoid creating closures in LINQ?

2 days ago 8
ARTICLE AD BOX

Let's say I have this method. Assume Items is an array of strings:

public int GetCount(char c) { return Items.Count(x => x.Contains(c)); }

I know that C# creates a closure for Count(x => x.Contains(c)) every time the method is called, because the local variable c is captured.

However, I was curious to know if a [ThreadStatic] field and a static local function could be used to cleverly avoid the creation of a closure:

[ThreadStatic] private static char _c; public int GetCount(char c) { _c = c; return Items.Count(func); static bool func(string x) => x.Contains(_c); }

Would that stop the creation of a closure?

Read Entire Article