StyleCop Analyzers Documentation

repository·master·Indexed 25 days ago

https://github.com/dotnetanalyzers/stylecopanalyzers

An implementation of StyleCop rules using the .NET Compiler Platform (Roslyn) to enforce consistent coding styles and provide automated code fixes. Includes documentation on installing the StyleCop.Analyzers NuGet package, configuring rule severity via rule set files, and customizing behavior using stylecop.json. Covers rule areas such as spacing (SA1000-), readability (SA1100-), naming (SA1300-), and alternative rules (SX0000-), as well as compatibility mappings for C# and Visual Studio versions.

Tokens
113K
Snippets
311
Records
536
Agent score
83%

What's inside StyleCop Analyzers

  1. Understand StyleCop.Analyzers rule areas

    master

    StyleCop.Analyzers organizes its style and consistency warnings into several rule areas. Understanding these areas helps you navigate the documentation for specific rule violations:

    • Special Rules (SA0000-): Special functionality such as workarounds or configuration errors.
    • Spacing Rules (SA1000-): Spacing requirements around keywords and symbols.
    • Readability Rules (SA1100-): Code formatting and readability standards.
    • Ordering Rules (SA1200-): Standard ordering schemes for code contents.
    • Naming Rules (SA1300-): Naming requirements for members, types, and variables.
    • Maintainability Rules (SA1400-): Rules focused on improving code maintainability.
    • Layout Rules (SA1500-): Code layout and line spacing.
    • Documentation Rules (SA1600-): Content and formatting of code documentation.
    • Alternative Rules (SX0000-): Non-standard extensions to default StyleCop behavior.
  2. C# 7.2 APIs supported via light-up

    master
    StyleCop.Analyzers supports C# 7.2 APIs through a 'light-up' mechanism. This allows the analyzers to utilize newer Roslyn APIs (such as Operation Blocks and advanced Operation Analysis) even when running in environments that might not natively support the latest compiler features. This includes access to OperationBlockStartAnalysisContext, OperationBlockAnalysisContext, and OperationBlockEndAction for more granular semantic analysis.
  3. C# 7.3 APIs supported via light-up

    master
    StyleCop.Analyzers supports specific C# 7.3 APIs through a mechanism called 'light-up'. This allows the analyzers to work with newer Roslyn APIs even when the underlying execution environment might be constrained. The supported APIs include various semantic and syntax features from the Microsoft.CodeAnalysis namespace, such as data flow analysis, compilation options, and specific operation kinds (e.g., Discard, Tuple binary operators).
  4. Configure StyleCop Analyzers using rule sets and stylecop.json

    master

    StyleCop Analyzers is configured via two mechanisms:

    1. Code analysis rule set files: Used to enable/disable individual rules and configure their severity. These are standard Visual Studio rule sets.
    2. stylecop.json: Used to specify project-specific text (like company names or copyright headers) and fine-tune the behavior of specific rules.

    You can find an example of the default rule set configuration here.

  5. Fix SA1626: Single-line comments must not use documentation-style slashes

    master

    The rule SA1626 (Documentation Rules) triggers when a single-line comment begins with three forward slashes (///). In C#, three slashes are reserved for XML documentation headers.

    To fix this violation:

    • Use exactly two slashes (//) for standard single-line comments.
    • Use four slashes (////) when commenting out lines of code to clearly differentiate them from standard comments.
    • Use three slashes (///) only for XML documentation headers.
  6. Fix SA1401: Fields Must Be Private

    master

    The SA1401 rule (part of StyleCop.CSharp.MaintainabilityRules) requires that all instance fields within a C# class be declared with private access. Using properties instead of public fields allows you to change the internal implementation without breaking the class interface.

    Exemptions:

    • Fields within C# structs can have any access level.
    • static readonly fields are exempt (commonly used as constants).
    • readonly instance fields are not exempt; they must still be private.
    • The C# 8 readonly modifier on struct members does not affect this rule.
    ## How to fix violations
    
    To fix a violation of this rule, make the field private and add a property to expose the field outside of the class.
  7. Fix SA1601: Partial Elements Must Be Documented

    master

    The SA1601 rule requires that every partial element (such as a partial class or partial method) has a documentation header. A violation occurs if the header is missing or empty.

    To avoid issues with SDK documentation tools merging or ignoring documentation, follow this pattern:

    1. Main Part: Use the standard <summary> tag to provide the official SDK documentation.
    2. Other Parts: Omit the <summary> tag and use the <content> tag instead. The <content> tag is ignored by SDK documentation tools but helps with code readability and maintainability.

    Example Fix

    /// <summary>
    /// Represents a customer in the database.
    /// </summary>
    public partial class Customer
    {
    }
    
    /// <content>
    /// Contains auto-generated functionality for the Customer class.
    /// </content>
    public partial class Customer
    {
    }
    /// <summary>
    /// Represents a customer in the database.
    /// </summary>
    public partial class Customer
    {
    }
    
    /// <content>
    /// Contains auto-generated functionality for the Customer class.
    /// </content>
    public partial class Customer
    {
    }
  8. Enable IntelliSense for stylecop.json

    master

    To enable IntelliSense (code completion, quick info) in Visual Studio while editing stylecop.json, add a $schema reference to the top level of your file:

    {
      "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json"
    }

    If the schema appears out-of-date, right-click anywhere in the stylecop.json document and select Reload Schemas.

    {
      "$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json"
    }
  9. Fix SA1212: Property accessors must follow order

    master

    The SA1212 rule (PropertyAccessorsMustFollowOrder) requires that a get accessor appears before any set or init accessor within a property or indexer. This rule also applies to readonly getters in structs; a readonly get must appear before any set or init accessor.

    To fix a violation, move the get accessor so that it precedes the set or init accessor.

    // Violates SA1212
    public string Name
    {
        set { this.name = value; }
        get { return this.name; }
    }
    
    // Complies with SA1212
    public string Name
    {
        get { return this.name; }
        set { this.name = value; }
    }
  10. Fix SA1603 XML documentation violations

    master

    To fix an SA1603 violation, ensure that all XML nodes in your documentation headers are valid and can be parsed by a standard XML parser. Ensure every opening tag has a corresponding, correctly spelled closing tag.

    // Invalid: The closing tag is misspelled
    /// <summary>
    /// An example of badly formed Xml.
    /// </summa3ry>
    public class Example
    {
    }
    
    // Fixed: Use a valid closing tag
    /// <summary>
    /// An example of valid Xml.
    /// </summary>
    public class Example
    {
    }
  11. Share StyleCop Configuration via NuGet

    master

    To reuse stylecop.json and custom rulesets across multiple solutions, package them into a NuGet package and use a .props file to inject them into projects.

    1. Create a .nuspec containing stylecop.json, your .ruleset, and a .props file.
    2. In the .props file, set CodeAnalysisRuleSet and add stylecop.json to AdditionalFiles.
    3. Consume the NuGet package in your target projects.
    <!-- Example .props file content -->
    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
          <CodeAnalysisRuleSet>$(MSBuildThisFileDirectory)\..\acme.stylecop.ruleset</CodeAnalysisRuleSet>
      </PropertyGroup>
      <ItemGroup>
          <AdditionalFiles Include="$(MSBuildThisFileDirectory)\..\stylecop.json" Link="stylecop.json" />
      </ItemGroup>
    </Project>