You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Static field order in a [Constraints] class can hand a rule a null #48
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>]publicstaticpartialclassOrderRules{publicstaticreadonlyConstraint<Order>ConfirmingTwiceIsConfirmingOnce=Constraints<Order>.Idempotent(o =>o.Confirm(Clerk));privatestaticreadonlyUserClerk=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.
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.
Activity
Mpdreamz commentedon Nov 19, 2026
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)readsClerkinside 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.