Repository navigation
SA1201: Add opt-in member ordering by name - #4431
Conversation
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.
|
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. |
|
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 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. |
|
Like @vossnc , we rely on CodeMaid for that purpose and it is decaying, so this would be very nice for us. |
|
Thanks @vossnc. That additional context and compelling data that this is actually a popular feature is sufficient justification. I'll review this. |
There was a problem hiding this comment.
🟡 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
nameordering 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
There was a problem hiding this comment.
🟡 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
Add the new resource key to both localized resource files Prevent name-ordering fixes from moving suppressed members · New Add runtime-initializer preservation regression for name ordering · New Add regression tests for auto and partial layout ordering Test event ordering diagnostics, fixes, and layout safeguards
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.
There was a problem hiding this comment.
🟡 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
Add the new resource key to both localized resource files Fix All leaves kind-order diagnostics after name grouping · New Preserve generated attributes on partial type declarations · New Add Fix All coverage for combined kind and name ordering · New Add runtime-initializer preservation regression for name ordering Add regression tests for auto and partial layout ordering Test event ordering diagnostics, fixes, and layout safeguards
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.
There was a problem hiding this comment.
🔵 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
Add the new resource key to both localized resource files Add Fix All coverage for combined kind and name ordering Add runtime-initializer preservation regression for name ordering Add regression tests for auto and partial layout ordering Test event ordering diagnostics, fixes, and layout safeguards
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 Report❌ Patch coverage is 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:
|



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
nameto the current list of ordering traits.The same trait is available in
settings.orderingRules.elementOrderinstylecop.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
Performance
Compared Release analyzer assemblies against
masterat45026329using Roslyn 5.12.0. The harness loaded four projects fromStyleCopAnalyzers.slnxthroughMSBuildWorkspace: 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.nameThe 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
nameas a final trait in the existingelementOrdersetting the configuration shape you would like for this feature?