Skip to content

SA1201: Add opt-in member ordering by name - #4431

Merged
AArnott merged 7 commits into
DotNetAnalyzers:masterfrom
vossnc:codex/sa1201-member-name-order
Nov 24, 2026
Merged

AArnott merged 7 commits into
DotNetAnalyzers:masterfrom
vossnc:codex/sa1201-member-name-order

Conversation

@vossnc

@vossnc vossnc commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Motivation

Our team groups C# members by declaration kind, accessibility, and modifiers. We also want to keep equally ranked members in alphabetical order so declarations are easier to find and new members land in consistent locations. An opt-in SA1201 setting lets us share that convention through repository configuration and use the same analyzer in IDE cleanup and CI.

CodeMaid offers an option to alphabetize members within a group. JetBrains Rider and ReSharper support name-based ordering through file layout patterns, and a community layout for StyleCop uses the member name as the final sort key. CodeMaid option · StyleCop layout for Rider and ReSharper

This builds on the customizable member-kind ordering introduced in #4324. The earlier requests for configurable member ordering provide context. #1610, #2541, discussion #4317.

Configuration and behavior

Append name to the current list of ordering traits.

[*.cs]
stylecop.ordering.elementOrder = kind, accessibility, constant, static, readonly, name

The same trait is available in settings.orderingRules.elementOrder in stylecop.json. The default trait list stays the same. SA1201 uses case-sensitive ordinal comparison between adjacent members of the same declaration kind and ordering group. Equal names retain their relative order.

For example, the fix sorts two constants with the same accessibility.

 public class Options
 {
-    public const int Zulu = 2;
     public const int Alpha = 1;
+    public const int Zulu = 2;
 }

Name ordering preserves runtime-initializer order, the order of module initializers, and instance member order where layout or record behavior requires it. It skips COM interop types, including public types exposed by assembly-level COM visibility. Fix All respects warning pragma suppression and runs the name-ordering pass for SA1201 diagnostics.

Verification

  • Built the full solution in Debug and Release with warnings as errors.
  • Regenerated the analyzer files from an empty output directory and verified all 210 files.
  • Passed 545 Ordering tests with the C# 6 test project and 932 with the C# 15 test project on the current branch base. Regression coverage includes both configuration sources, COM and layout, partial and nested module initializers, effective constant traits, and Fix All with rule and pragma suppression.
dotnet build StyleCopAnalyzers.slnx -c Debug -m:1 -warnaserror
dotnet build StyleCopAnalyzers.slnx -c Release -m:1 -warnaserror
dotnet test test/StyleCop.Analyzers.Test -c Debug -f net10.0 --no-build --filter "FullyQualifiedName~OrderingRules"
dotnet test test/StyleCop.Analyzers.Test.CSharp15 -c Debug -f net10.0 --no-build --filter "FullyQualifiedName~OrderingRules"

Performance

Compared Release analyzer assemblies against master at 45026329 using Roslyn 5.12.0. The harness loaded four projects from StyleCopAnalyzers.slnx through MSBuildWorkspace: the analyzer, the code fixes, and the base and C# 15 test projects targeting .NET 10. It enabled and ran only SA1201 in each analysis, used the same source inputs across the three modes, and rotated their order over 15 measured rounds after three warm-up rounds. The opt-in run used distinct syntax-tree instances to keep the settings cache isolated.

Mode Median wall time Median summed SA1201 time SA1201 diagnostics
Master 3.122 s 13.0 ms 0
Feature with defaults 2.978 s 16.1 ms 0
Feature with name 3.119 s 2,576 ms 2,695

The analyzer time sums work performed in parallel. The opt-in run is a first pass over 1,392 syntax trees with unsorted members. The benchmark measures analysis and reporting. Code-fix correctness is covered by the regression tests.

Feedback

Is name as a final trait in the existing elementOrder setting the configuration shape you would like for this feature?

Enable projects to order equally ranked members by name using existing centralized StyleCop configuration. Preserve runtime ordering and source suppression boundaries in the code fix.
@AArnott

AArnott commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Thanks for contributing. I'm on the fence on this one. You've already put in the work and demonstrated the perf impact, which is great.
On the other hand, I've never heard anyone ask for this, and it adds a decent amount of code that we'll maintain going forward. StyleCop.Analyzers isn't a great place for putting in rules that only one repo or team needs.

@vossnc

vossnc commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, Andrew. I’ve used alphabetical ordering within member groups for years and helped make it part of the coding standards at both my previous and current companies. In larger classes, it gives everyone a predictable place to find or add a declaration.

We’ve relied on CodeMaid for this, but it hasn’t had a new release in years. When its reorganizer dropped modifiers from a public ref readonly struct, it made me look for a longer-term way to keep the convention as we adopt newer C# features. CodeMaid releases

Other developers have asked for automatic method alphabetization in Visual Studio, and SA1201ier offers alphabetical sorting within existing member groups. For teams already using StyleCop, an opt-in setting would let them apply the same convention in IDE cleanup and CI. Visual Studio request · SA1201ier

I understand the maintenance concern. The PR adds about 500 lines of production code and 900 lines of tests. Most of the production changes are in the code fix and its helper. The tests cover cases where moving declarations gets tricky, including COM member order, initializers, and #pragma suppression.

@Otterprinz

Copy link
Copy Markdown

Like @vossnc , we rely on CodeMaid for that purpose and it is decaying, so this would be very nice for us.

@AArnott

AArnott commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Thanks @vossnc. That additional context and compelling data that this is actually a popular feature is sufficient justification. I'll review this.

@AArnott
AArnott marked this pull request as ready for review November 23, 2026 16:34
Copilot AI balanced review requested due to automatic review settings November 23, 2026 16:34

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new resource key is missing from the Russian and Chinese resource files, breaking localization completeness checks.

3 open issues
1 file not reviewed
  • src/StyleCop.Analyzers/Lightup/.generated/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/OrderingResources.Designer.cs: Generated file
What changed in this PR

Adds opt-in alphabetical member ordering to SA1201, building on configurable member-kind ordering while leaving the default behavior unchanged.

Changes:

  • Adds the name ordering trait with case-sensitive ordinal comparison.
  • Extends single fixes and Fix All with safeguards for initialization, layout, COM interop, and suppression.
  • Adds regression tests and documents the configuration and safety boundaries.
File Description
test/​StyleCop.Analyzers.Test/​OrderingRules/​SA1201UnitTests.NameOrderReviewRegressions.cs Covers COM visibility, effective traits, and Fix All suppression.
test/​StyleCop.Analyzers.Test/​OrderingRules/​SA1201UnitTests.MethodNameOrder.cs Tests method sorting, overload stability, and opt-in behavior.
test/​StyleCop.Analyzers.Test/​OrderingRules/​SA1201UnitTests.MemberNameOrder.cs Tests fields, properties, initialization, layout, and kind grouping.
test/​StyleCop.Analyzers.Test.CSharp9/​OrderingRules/​SA1201CSharp9UnitTests.MemberNameOrder.ReviewRegressions.cs Covers nested and partial module-initializer boundaries.
test/​StyleCop.Analyzers.Test.CSharp9/​OrderingRules/​SA1201CSharp9UnitTests.MemberNameOrder.cs Tests module-initializer and record-order preservation.
test/​StyleCop.Analyzers.Test.CSharp8/​OrderingRules/​SA1201CSharp8UnitTests.MethodNameOrder.cs Tests EditorConfig configuration.
StyleCop.Analyzers/​StyleCop.Analyzers/​Settings/​stylecop.schema.json Allows name in the ordering-trait schema.
src/​StyleCop.Analyzers/​Settings/​ObjectModel/​OrderingTrait.cs Defines the new ordering trait.
src/​StyleCop.Analyzers/​Settings/​ObjectModel/​MemberKindOrder.cs Exposes shared member-priority calculation.
src/​StyleCop.Analyzers/​OrderingRules/​SA1201ElementsMustAppearInTheCorrectOrder.cs Reports name-order violations with safety checks.
src/​StyleCop.Analyzers/​OrderingRules/​OrderingResources.resx Adds the name-order diagnostic message.
src/​StyleCop.Analyzers/​Lightup/​.generated/​Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/​Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/​OrderingResources.Designer.cs Adds the generated message accessor.
src/​StyleCop.Analyzers/​Helpers/​MemberNameOrder.cs Centralizes sortable-member identification and safety checks.
src/​StyleCop.Analyzers.CodeFixes/​OrderingRules/​ElementOrderCodeFixProvider.cs Implements name sorting for single fixes and Fix All.
documentation/​zh-cn/​SA1201.md Documents name ordering in Simplified Chinese.
documentation/​SA1201.md Documents name ordering and preservation guarantees.
documentation/​ru-ru/​SA1201.md Documents name ordering in Russian.
documentation/​cs-cz/​SA1201.md Documents name ordering in Czech.
documentation/​Configuration.md Describes the optional trait and EditorConfig usage.

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 24, 2026 12:40

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Both the individual fix and Fix All move effectively SA1201-suppressed members during name ordering instead of preserving their suppression.

5 open issues
1 file not reviewed
  • src/StyleCop.Analyzers/Lightup/.generated/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/OrderingResources.Designer.cs: Generated file

Review effort: Balanced

Honor local and global suppressions in both fix scopes. Preserve COM, EventSource, explicit XML contracts, generated code, and decimal initialization order. Use the established SA1201 kind grouping across syntax forms.
Copilot AI balanced review requested due to automatic review settings November 24, 2026 13:44

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Name-order fixes can introduce a new kind-order diagnostic and move generated partial declarations, while integration with configurable kind ordering lacks regression coverage.

7 open issues
1 resolved since last review
1 file not reviewed
  • src/StyleCop.Analyzers/Lightup/.generated/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/OrderingResources.Designer.cs: Generated file

Review effort: Balanced

Share name grouping across diagnostics and code fixes, protect generated partial declarations, and preserve higher-priority ordering constraints in single and bulk fixes.
Reuse the existing ordering comparisons when deciding whether a name fix would move an ordering violation. Keep the default kind order in one place for the analyzer and code fix.
Use SA1202 member eligibility for name-order boundaries and preserve accessibility exceptions for dependent fields. Key the Fix All dependency cache by original type declaration and cover the unsafe and safe reorders.
Copilot AI balanced review requested due to automatic review settings November 24, 2026 17:30

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Maintainer review is needed to assess IDE responsiveness given the reported opt-in SA1201 analysis-time increase from 13 ms to 2,576 ms and to accept the new elementOrder configuration contract.

5 open issues
2 resolved since last review
1 file not reviewed
  • src/StyleCop.Analyzers/Lightup/.generated/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp/Microsoft.CodeAnalysis.ResxSourceGenerator.CSharp.CSharpResxGenerator/OrderingResources.Designer.cs: Generated file

Review effort: Balanced

@codecov

codecov Bot commented Nov 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.86260% with 87 lines in your changes missing coverage. Please review.
✅ Project coverage is 97.47%. Comparing base (78cb59b) to head (76ae43d).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4431      +/-   ##
==========================================
+ Coverage   97.44%   97.47%   +0.03%     
==========================================
  Files        1379     1391      +12     
  Lines      160746   163347    +2601     
  Branches     5812     5943     +131     
==========================================
+ Hits       156632   159217    +2585     
+ Misses       2614     2603      -11     
- Partials     1500     1527      +27     
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@AArnott
AArnott merged commit 059044f into DotNetAnalyzers:master Nov 24, 2026
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants