How it works...

The StypeCop analyzers contain the following categories of style rules:

The code example that we provided had the following StyleCop diagnostics by category:

  • Spacing:
    • SA1025 (Code must not contain multiple whitespace characters in a row)
  • Readability:
    • SA1101 (Prefix local calls with this)
  • Ordering:
    • SA1200 (Using directive must appear within a namespace declaration)
  • Naming:
    • SA1300 (Element "method" must begin with an uppercase letter)
    • SA1303 (Const field names must begin with uppercase letter)
  • Maintainability:
    • SA1401 (Field must be private)
    • SA1402 (File may only contain a single type)
  • Layout:
    • SA1502 (Element must not be on a single line)
    • SA1503 (Braces must not be omitted)
    • SA1505 (An opening brace must not be followed by a blank line)
  • Documentation:
    • SA1600 (Elements must be documented)
    • SA1633 (The file header is missing or not located at the top of the file)

The StyleCop analyzers package also comes with code fixes for certain rules to fix the violations.

The StyleCop analyzers can be installed either as a NuGet package (http://www.nuget.org/packages/StyleCop.Analyzers/) for specific C# projects/solutions or as a VSIX Extension enabled for all C# projects. The NuGet package enables the build-time StyleCop diagnostics and hence is the recommended way of installing the analyzers.

The code style is generally considered to be a very subjective matter, and hence it is very important that individual rules can be selectively enabled, suppressed, or configured by the end user.

  • StyleCop rules can be enabled or suppressed using the code analysis ruleset files (see the recipe, Using ruleset file and ruleset editor to configure analyzers, in Chapter 2, Consuming Diagnostic Analyzers in .NET Projects for reference).
  • Stylecop rules can be configured and tuned using a stylecop.json file added to the project as an additional non-source file. For example, consider the ordering rule SA1200 (using directive must appear within a namespace declaration) at (http://www.nuget.org/packages/StyleCop.Analyzers/). By default, this rule reports violations if using directives are placed at the top of the file outside a namespace declaration. However, this rule can be configured to be its semantic opposite and require using directives to be outside a namespace declaration and report violations if they are inside, using the following stylecop.json:
{
"settings": {
"orderingRules": {
"usingDirectivesPlacement": "outsideNamespace"
}
}
}
The StyleCop analyzers repo has thorough documentation for each category of rules, as well as individual style rules. You can find the documentation at https://github.com/DotNetAnalyzers/StyleCopAnalyzers/tree/master/documentation.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset