Skip to content

Latest commit

 

History

History
115 lines (89 loc) · 2.81 KB

SA1201.md

File metadata and controls

115 lines (89 loc) · 2.81 KB

SA1201

TypeName SA1201ElementsMustAppearInTheCorrectOrder
CheckId SA1201
Category Ordering Rules

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
  • Properties
  • Indexers
  • Methods
  • Structs
  • Classes*

📝 For ordering purposes, C# 9 records are treated as classes.

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();
    }
}

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", "SA1201:ElementsMustAppearInTheCorrectOrder", Justification = "Reviewed.")]
#pragma warning disable SA1201 // ElementsMustAppearInTheCorrectOrder
#pragma warning restore SA1201 // ElementsMustAppearInTheCorrectOrder