Skip to content

C#: Use static constructor as enclosing callable for static member initializers.#22186

Draft
michaelnebel wants to merge 4 commits into
github:mainfrom
michaelnebel:csharp/staticfieldenclosingcallable
Draft

C#: Use static constructor as enclosing callable for static member initializers.#22186
michaelnebel wants to merge 4 commits into
github:mainfrom
michaelnebel:csharp/staticfieldenclosingcallable

Conversation

@michaelnebel

@michaelnebel michaelnebel commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

It appears that the cs/useless-assignment-to-local produces some false positives for static members.
That is, the query incorrectly reports x as being a useless assignment in

public static readonly IEnumerable<int> StaticQueryBackedField =
        from x in new[] { 1, 2, 3 }
        where x > 1
        select x;

The root cause of the problem is that the static member initializers don't have an enclosing callable (which affects the SSA logic and this bubbles up into the results of cs/useless-assignment-to-local query). In this PR we fix the problem by using the static constructor as the enclosing callable for the control flow elements/expressions of static member inititializers. For instance fields, there is a dedicated synthetic "object initializer" method (as there can exist multiple instance constructors). However, there is exactly one static constructor, so we can use that as the enclosing callable.

@github-actions github-actions Bot added the C# label Jul 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant