Table of Contents

SA1202: Elements should be ordered by access

Cause

An element within a C# code file is out of order within regard to access level, in relation to other elements in the code.

Rule description

A violation of this rule occurs when the code elements within a file do not follow a standard ordering scheme based on access level.

To comply with this rule, adjacent elements of the same type should be positioned in the following order by access level:

  • public
  • internal
  • protected internal
  • protected
  • private protected
  • private

📝 Static constructors and explicitly implemented interface methods, properties, indexers, and events are considered public for the purposes of this rule. Explicit interface events were treated as private by StyleCop Classic; treating them as public here is intentional and consistent with the other explicit interface members.

Complying with a standard ordering scheme based on access level can increase the readability and maintainability of the file and make it easier to identify the public interface that is being exposed from a class.

Interfaces and default interface members

Default interface members (including members with implementations and static interface members) follow the same access ordering as class members. Within an interface, public members should appear before internal, protected internal, protected, private protected, and private members.

Records and primary constructors

Records (including positional records) and record structs follow the same ordering rules as classes and structs. Primary constructor parameters that become properties do not change the expected access ordering for the remaining members.

Dependent fields

Fields whose initializers reference other non-constant fields of the containing type must be initialized in textual declaration order. A field with a higher access level is allowed to appear after a field with a lower access level when the field directly or transitively depends on the preceding field, or depends on another field that must appear after the preceding field.

How to fix violations

To fix an instance of this violation, order the elements in the file in the order described above.

How to suppress violations

[SuppressMessage("StyleCop.CSharp.OrderingRules", "SA1202:ElementsMustBeOrderedByAccess", Justification = "Reviewed.")]
#pragma warning disable SA1202 // ElementsMustBeOrderedByAccess
#pragma warning restore SA1202 // ElementsMustBeOrderedByAccess