Skip to content

Static field order in a [Constraints] class can hand a rule a null #48

Open

Description

@Mpdreamz

In a [Constraints] class, a static helper declared below the rules that use it is still null when those rules initialise. The rule is then built with a null argument.

What happened

[Constraints<Order>]
public static partial class OrderRules
{
    public static readonly Constraint<Order> ConfirmingTwiceIsConfirmingOnce = Constraints<Order>.Idempotent(o => o.Confirm(Clerk));

    private static readonly User Clerk = new("clerk");   // still null when the rule above captured it
}

C# initialises static fields in declaration order. A nullable warning caught it here, but only because Confirm took a non-nullable argument. A nullable parameter would have run the rule with null silently.

What would you like instead

The source generator already reads the class. It could report a diagnostic when a constraint's initializer reads a static field of the same class that is declared later, with a fix that moves the field up. Short of that, a line in the [Constraints] docs.

Version or commit

main at f12a258 (0.1.1).

Estimated work: half a day for the diagnostic; an hour for the docs.

Activity

  1. Mpdreamz commented on Nov 19, 2026

    @Mpdreamz
    ContributorAuthor

    PR #101 adds generator warning NECG030 for a [Constraints] rule whose initializer reads a static field declared below it in the same file.

    One correction to the report: in the example, o => o.Confirm(Clerk) reads Clerk inside a lambda, so it runs when the rule is checked, after every static is set. That form is safe, and the diagnostic deliberately skips lambdas and local functions. The null happens when the read is direct, e.g. Constraints<Order>.Always(Make(Clerk)). That is what the diagnostic flags.

    I did not add a code fix. The message tells you to move the field up. Declarations across partial files are not checked, since their order is undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementAn existing capability improved (minor bump)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions