Table of Contents

SA1201: Elements should appear in the correct order

Cause

An element within a C# code file is out of order in relation to the 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.

To comply with this rule, elements at the file root level or within a namespace should be positioned in the following order:

  • Extern Alias Directives
  • Using Directives
  • Namespaces
  • Delegates
  • Enums
  • Interfaces
  • Structs
  • Classes

Within a class, struct, or interface, elements should be positioned in the following order:

  • Fields
  • Constructors
  • Finalizers (Destructors)
  • Delegates
  • Events
  • Enums
  • Interfaces
  • Extension blocks
  • Properties
  • Indexers
  • Conversion operators
  • Operators
  • Methods
  • Structs
  • Classes

📝 For ordering purposes, C# 9 records are treated as classes, and C# 10 record structs are treated as structs.

📝 C# 14 extension blocks (extension(...) { }) are ordered as their own element type, after interfaces and before properties.

The member-kind order inside types can be customized with orderingRules.memberKindOrder, or stylecop.ordering.memberKindOrder in EditorConfig. A partial list orders contiguous groups of the named kinds; unnamed kinds may occur between, but not inside, those groups. File and namespace ordering is unchanged. Without this setting, the predefined ordering above still applies.

Complying with a standard ordering scheme based on element type can increase the readability and maintainability of the file and encourage code reuse.

When implementing an interface, it is sometimes desirable to group all members of the interface next to one another. This will sometimes require violating this rule, if the interface contains elements of different types. This problem can be solved through the use of partial classes.

  1. Add the partial attribute to the class, if the class is not already partial.

  2. Add a second partial class with the same name. It is possible to place this in the same file, just below the original class, or within a second file.

  3. Move the interface inheritance and all members of the interface implementation to the second part of the class.

For example:

/// <summary>
/// Represents a customer of the system.
/// </summary>
public partial class Customer
{
    // Contains the main functionality of the class.
}

/// <content>
/// Implements the ICollection class.
/// </content>
public partial class Customer : ICollection
{
    public int Count 
    { 
        get { return this.count; }
    }

    public bool IsSynchronized 
    { 
        get { return false; }
    }

    public object SyncRoot 
    { 
        get { return null; }
    }

    public void CopyTo(Array array, int index)
    {
        throw new NotImplementedException();
    }
}

Ordering members by name

Add name as the last entry in orderingRules.elementOrder to break ties between adjacent members of the same SA1201 member kind and ordering group. SA1201 compares member names using a case-sensitive ordinal comparison. Field-like events and events with accessors share a kind. Record classes share a kind with classes, and record structs share a kind with structs. With the default kind order, placing static before kind keeps constants and explicitly static fields in separate name-ordering groups. When static follows the default kind order, classes and record classes stay in separate name-ordering groups to respect SA1204. If a group starts with a member that is out of order under an earlier trait, name sorting keeps that member at the front of the group.

The rule skips name ordering in types marked for COM interop, including public types exposed by assembly-level COM visibility and public types covered by an explicitly configured assembly-level COM class interface. An explicit [ComVisible(false)] at the assembly or type level takes precedence over the assembly-level class interface setting. The rule also skips name ordering in classes derived from EventSource to preserve implicit event IDs.

Module initializers and nested types containing them keep their order and split name-ordering groups. In records and types with fixed layout, name ordering preserves the order of instance fields, properties, and field-like events. Instance storage members in XML contracts marked with [XmlRoot] or [XmlType] also keep their declaration order. Runtime initializers retain their relative order.

The code fix respects #region and #endregion boundaries and leaves generated declarations and declarations in #line hidden regions in place. Both the individual fix and Fix All respect #pragma warning disable. They leave declarations with a local or global SuppressMessage for SA1201 in place. An unsuppressed member can still move ahead of those declarations.

How to fix violations

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

Ordering violations are still reported across preprocessor directives. The element-order code fix does not reorder members when the move would involve directives, since this could change conditional compilation or other directive behavior. Reorder these elements manually while preserving the directive boundaries.

How to suppress violations

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