Updated on
StyleCop.Analyzers is a NuGet package of Roslyn analyzers that enforce a C# style guide at build time. We install it, pick which of its rules matter to our team, and the compiler does the arguing from then on.
Two files do the configuring, and they do different jobs. An .editorconfig file decides how loudly a rule complains, and a stylecop.json file decides what that rule considers correct.
Let’s get started.
What Is StyleCop.Analyzers?
StyleCop.Analyzers is a set of Roslyn analyzers that check C# source against the StyleCop style rules while we type and while we build. It ships as a NuGet package, so nothing is installed into Visual Studio and every developer on the team gets the same rules from the same project file.
Each rule has an identifier, almost always starting with SA, and a category. SA1101 asks us to prefix local calls with this, SA1633 wants a file header, SA1206 fixes the order of declaration keywords. Violations surface in the error list as warnings, errors or suggestions, depending on how we configure them. Warnings and errors also show in the build output.
Two things decide what we see. Severity comes from an .editorconfig file or from Visual Studio’s rule set UI, and the rules’ own options come from a stylecop.json file.
A stylecop.json file cannot raise or lower a severity, and on the stable 1.1.118 release an .editorconfig file cannot tell a rule what our company name is.
We can find the complete list of default rules and their grouping on the StyleCop GitHub, and our introduction to the Roslyn compiler explains how Roslyn analyzers work under the compiler.
Now that we know a little bit more about StyleCop, let’s see how we can set it up!
How Do We Install StyleCop.Analyzers in a Project?
Installing StyleCop.Analyzers takes one package reference. In a new Web API project, we add it with dotnet add package StyleCop.Analyzers, or through the NuGet package manager in Visual Studio.
The reference belongs in the consuming project only, and we do not have to configure it: the package declares itself a development dependency, so the CLI writes <PrivateAssets>all</PrivateAssets> onto it for us.
A freshly generated Web API project whose code compiled without a single warning produced ten StyleCop warnings from eight rules on our machine, because the default rule set is strict about file headers, blank lines and ordering. That is the moment to decide which rules our team wants rather than silencing them one by one.
Since the .NET 8 SDK, dotnet new webapi creates a minimal API project, so the WeatherForecastController this article works with only appears when we ask for controllers explicitly, with --use-controllers.
We can create the project using the ASP.NET Core Web API template in Visual Studio, or using .NET CLI:
dotnet new webapi --use-controllers
After the project is successfully created, let’s build it. If we take a look at the error list window, we can see that there are no errors, and no warnings or information from our code.
Now, we can install StyleCop and see what happens. To do so, we can install the StyleCop.Analyzers NuGet package:
dotnet add package StyleCop.Analyzers
If we build the project again, we can see a whole new list of warnings coming from our newly installed StyleCop (our capture is from 2023, when the template produced 15 of them):
Among other things, in the error window, we can see the warning code, its description, and that it comes from the project named StyleCop. Also, we can see that the Suppression State is Active.
If we want to learn more about each warning we can click on the Code id and it will redirect us to the StyleCop GitHub page. There we can find documentation for the selected rule. For example, if we want to learn more about the rule SA1137 Elements should have the same indentation, we will end up on the rule documentation page.
Now we know how to enable StyleCop Analyzers in our project, but we often want to customize the given rule set to fit our specific needs, let’s find out how.
Which StyleCop.Analyzers Version Should We Install?
dotnet add package StyleCop.Analyzers installs 1.1.118, the latest stable release, and that release is from 29 April 2019. The project’s own version table states that C# 8.0 support needs “v1.2.0-beta or higher”, so the stable package predates every language feature from C# 8 onward, including file-scoped namespaces, records and collection expressions.
The 1.2.0 line is where current C# support lives, and it has been in beta since September 2019. The newest prerelease, 1.2.0-beta.556, was published on 20 December 2023. The repository is still maintained, but no stable release has followed.
Building the same net10.0 files under both, 1.1.118 reports a spacing violation on an inline collection expression that is not a violation, and inside a file-scoped namespace it reports nothing at all about a file holding several types. The beta gets both right. Whichever line we choose, we pin the exact version rather than floating, because a beta that moves under a shared rule set changes everyone’s build at once.
Our sample pins 1.1.118, the line for a team whose policy rules out prerelease packages, while a codebase that uses records, file-scoped namespaces or collection expressions gets more accurate results from 1.2.0-beta.556. The C# version table is in the project’s README.
How Do We Customize StyleCop Analyzers Rules?
Four places can change what StyleCop reports, and each one owns a different job.
An .editorconfig file sets severity, one rule at a time, with entries like dotnet_diagnostic.SA1101.severity = suggestion. It is the only place severity belongs, because the compiler reads it on every build and it travels with the repository.
A stylecop.json file sets rule options, not severity: the company name in file headers, the order of members, where using directives go. It has to be registered as an AdditionalFiles item or the analyzers never read it.
A GlobalSuppressions.cs file turns one rule off for one named member, or for the whole project, with a justification other developers can read.
A #pragma warning disable pair turns one rule off for the lines between it and its #pragma warning restore.
Severity is a team decision, so it belongs in .editorconfig. A suppression is an exception, so it should name what it excuses and why.
Here are those places side by side, plus the Visual Studio route:
| Place | Controls | Scope | Example entry |
|---|---|---|---|
.editorconfig | Rule severity | Whole repository, or a path pattern | dotnet_diagnostic.SA1101.severity = suggestion |
stylecop.json | Rule options and settings | The project that registers it | "companyName": "CodeMaze" |
GlobalSuppressions.cs | Turning one rule off | One named type or member, or the whole assembly | [assembly: SuppressMessage(...)] |
#pragma warning disable | Turning one rule off | The lines between disable and restore | #pragma warning disable SA1137 |
| Visual Studio rule set UI | Rule severity | Writes into .editorconfig for us | Right-click the rule, Set severity |
We start with severity, then suppressions, then stylecop.json.
Changing Rule Severity
Let’s say that our team agrees that we don’t want to treat rule SA1101 "Prefix local calls with this" as a warning, but as a suggestion. The first way we can do it is to go directly into the .editorconfig file and edit it there.
Using the .editorconfig File
In .NET, .editorconfig file is a configuration file that is used to enforce coding style conventions. It specifies rules for code formatting, such as indentation, line spacing, and more. All of this helps to ensure consistency across developers by placing the file in the project’s root directory and making it available for everyone by checking it in the version control.
To get access to this file in our project, in Visual Studio we can go to Tools then Options. Here, and under the C# section, we search for the code style general section and click Generate .editorconfig file from settings. Then, we can save the generated file in the root of our repository and name it .editorconfig:
Now, let’s open the file, and under the Analyzers tab search for the rule we want to modify, in our case the id is SA1101:
Here, under the severity, we want to set it as a suggestion. Now, all we need to do is save our changes to the .editorconfig file and the new severity will be applied to our project.
Going Through Visual Studio
Another way to do it is to open the StyleCop Analyzers under our project’s dependencies. There, we can see all the defined rules:
Right-clicking on a given rule will open a context menu where we can click on Set severity. There we can choose our desired severity level, which in our case would be a suggestion.
If we go with this approach, we will see that .editorconfig file got included in the code project, since we changed the default rule set.
Suppressing Rules
When working with StyleCop, one more common requirement can be to suppress a certain rule.
One way we can do it is to set its severity to None or Silent. The difference between the two is that by using None we completely disable the rule. On the other hand with Silent the rule violation is detected and recorded but without generating visible warnings or errors.
Another way to suppress a rule is to hover over a place where the rule violation is appearing:
Here, we can click on Show potential fixes or use a shortcut to access the action menu by pressing “Alt+Enter” or “Ctrl + .” Now we get a menu with multiple options to suppress the rule violation:
If we decide to do it in Source, we will see our file got modified:
#pragma warning disable SA1137 // Elements should have the same indentation //code which is breaking the rule #pragma warning restore SA1137 // Elements should have the same indentation
By using #pragma warning disable, we tell our compiler not to display the selected rule violation in certain places in our code. After it, we should add #pragma warning restore to re-enable the warning after the code block, restoring the default behavior.
Using Global Suppression File
If we wish to keep the suppression in a project-level file, we can choose the second option, in Suppression File. This will create a GlobalSuppressions.cs file inside our project folder. In our sample, the file ends up like this:
// <copyright file="GlobalSuppressions.cs" company="CodeMaze">
// Copyright (c) CodeMaze. All rights reserved.
// </copyright>
using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage(
"StyleCop.CSharp.ReadabilityRules",
"SA1137:Elements should have the same indentation",
Justification = "For testing purposes",
Scope = "member",
Target = "~F:StyleCop.Controllers.WeatherForecastController.Summaries")]
[assembly: SuppressMessage(
"StyleCop.CSharp.DocumentationRules",
"SA1600:Elements should be documented",
Justification = "For testing purposes")]
We use GlobalSuppressions.cs file to suppress specific StyleCop warnings or rule violations within certain projects. It allows us to selectively disable or ignore certain rules for specific sections of code or individual code.
To make it selective we use Scope and Target properties. The Scope property determines the level at which the suppression is applied. It can have values like namespaceanddescendants, type, member, or module, depending on the desired level of granularity. On the other hand, we use the Target property to specify the specific code element to which the suppression applies within the chosen scope. Its value depends on the selected Scope and should match the name or identifier of the target code element.
In our case, the rule suppression for rule “SA1137:Elements should have the same indentation” will be applied only to the Summaries field within the WeatherForecastController class.
The second suppression has no Scope or Target, so it turns SA1600 Elements should be documented off for the whole project. In a dotnet build of our sample, SA1600 does not fire anyway: the build reports SA0001 XML comment analysis is disabled due to project configuration instead, because the project does not set GenerateDocumentationFile. Once we set it to true, SA1600 flags ten undocumented elements, and this suppression is what keeps them quiet.
Also, we can see that we have Justification property. We can use this property to inform other team members why a certain rule was suppressed. If we don’t set it, we will also get a warning from StyleCop that it should be set.
Adding stylecop.json
In addition to .editorconfig and suppression files, to gain more control over StyleCop implementation we can use stylecop.json file. If we hover over an SA1600 or SA1633 violation, we get an Add StyleCop settings file to the project option and a preview of the added stylecop.json file:
This will create a stylecop.json file:
{
// ACTION REQUIRED: This file was automatically added to your project, but it
// will not take effect until additional steps are taken to enable it. See the
// following page for additional information:
//
// https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/EnableConfiguration.md
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"settings": {
"documentationRules": {
"companyName": "PlaceholderCompany"
}
}
}
First, we have a comment that says that we need to take additional steps to enable its usage. What this means is that we need to change the build action of the file. To do so, we need to go to the properties of the file and select that the build action is C# analyzer additional file:
Outside Visual Studio, we register the file in the project file instead. Our sample’s .csproj does it like this:
<ItemGroup> <AdditionalFiles Include="stylecop.json" /> </ItemGroup>
In the file, the JSON field $schema specifies the URI of the JSON schema file that defines the structure and validation rules for the stylecop.json file. In this case, the URI points to the schema file on the GitHub repository of StyleCop Analyzers. This lets a schema-aware editor check that the configuration file follows the correct schema.
Next, we have a settings section where we can configure the rules. We already have one section predefined, and it is a documentationRules section. Inside it, we can find a companyName property that we can replace with our desired name.
If we take a look at our existing warnings, we can see that we have a rule break SA1633 "The file header is missing or not located at the top of the file". Now, if we go to that rule break and hover over it, we can select Add file header:
In the preview of the added header, we can see it will generate a header with our company name at the top of the file. In our case, we renamed it to CodeMaze (our capture shows MyCompany, the name we had set at the time).
Now, let’s see how we can customize the ordering rules.
Customizing the Ordering Rules
Let’s say we want to define an array of strings:
private readonly static string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild",
"Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
If we do it like this, we get SA1206, “The ‘static’ modifier should appear before ‘readonly'”. SA1206 has no setting in stylecop.json, so we clear it by writing static before readonly, or we suppress it. Instead, stylecop.json controls the order of the members themselves. The ordering rules (SA1201 to SA1204 and SA1214) read an elementOrder array, so we can add one to the file:
{
// ACTION REQUIRED: This file was automatically added to your project, but it
// will not take effect until additional steps are taken to enable it. See the
// following page for additional information:
//
// https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/EnableConfiguration.md
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"settings": {
"documentationRules": {
"companyName": "CodeMaze"
},
"orderingRules": {
"elementOrder": [ "kind", "accessibility", "constant", "readonly", "static" ],
"usingDirectivesPlacement": "outsideNamespace"
}
}
}
We add a new section and name it orderingRules. Its elementOrder array lists the traits StyleCop sorts members by, in priority order. In our case, readonly comes before static, so a private readonly field declared below a private static one now gets SA1214, “Readonly fields should appear before non-readonly fields”, where the default order accepts it. Our sample keeps its readonly static field and its SA1206 warning on purpose, as the example of a rule that no stylecop.json setting changes.
The second setting, usingDirectivesPlacement, keeps using directives outside the namespace in our sample’s files. Without it, SA1200 asks for them inside.
This was just a simple example of how to add a change to a custom rule set. There are plenty of other possibilities for working with stylecop.json file. We can find a full list of possible customization with stylecop.json in their documentation.
What Are the Alternatives to StyleCop.Analyzers?
The first alternative to StyleCop.Analyzers is the .NET SDK we already have. Microsoft ships Roslyn analyzers with the SDK, and for projects targeting .NET 5 or later, code quality analysis is on by default. Those are the CA rules.
Code style rules, the IDE ones, are the nearest thing the SDK has, and they are disabled on command-line builds by default. Setting EnforceCodeStyleInBuild to true and giving the rules a severity in .editorconfig turns them into build warnings, which covers formatting, var preferences, expression bodies and accessibility modifiers without any third-party package. On our own sample, the IDE rules reproduced the this. qualification and modifier-order warnings, and the leading-underscore one after we wrote a naming rule for private fields.
Beyond that, Microsoft’s own documentation names StyleCop, Roslynator, Meziantou.Analyzer, xUnit Analyzers and SonarAnalyzer as examples of third-party analyzers. FxCop is not one of them: its package, Microsoft.CodeAnalysis.FxCopAnalyzers, was deprecated on NuGet and replaced by the SDK’s analyzers, which NuGet also carries as Microsoft.CodeAnalysis.NetAnalyzers.
We recommend starting with the built-in rules plus one third-party set.
Here are the options side by side, with the versions NuGet listed in October 2026:
| Analyzer | Version on NuGet, October 2026 | Ships with the SDK | What it is for |
|---|---|---|---|
.NET code quality rules (CA) | Part of the .NET SDK | Yes, on by default for .NET 5 and later | Correctness, security, performance |
.NET code style rules (IDE) | Part of the .NET SDK | Yes, but off on command-line builds until EnforceCodeStyleInBuild is true | Formatting and language style |
StyleCop.Analyzers | 1.1.118 stable, 1.2.0-beta.556 prerelease | No | The StyleCop style guide: layout, ordering, documentation, naming |
Roslynator.Analyzers | 5.0.1 | No | "A collection of 200+ analyzers for C#, powered by Roslyn" |
SonarAnalyzer.CSharp | 10.35.0.4138 | No | "Bugs, Vulnerabilities and Code Smells" |
Meziantou.Analyzer | 3.0.299 | No | Static analysis for bugs, security issues and best practices |
| FxCop analyzers | 3.3.2, deprecated | No | Superseded: NuGet marks it legacy and points at the .NET analyzers package |
Turning on the IDE rules takes two steps. First, we set the property in the project file:
<PropertyGroup> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> </PropertyGroup>
Then we give each rule we want enforced a severity in .editorconfig:
[*.{cs,vb}]
# IDE0040: Accessibility modifiers required (escalated to a build warning)
dotnet_diagnostic.IDE0040.severity = warning
The second fragment comes from the code analysis overview on Microsoft Learn, which also explains why the first one is needed: “Code-style analysis is disabled, by default, for all .NET projects on command-line builds.” To have these rules fixed rather than only reported, we can run the dotnet format command, which reads the same .editorconfig.
Conclusion
In this article, we saw how implementing StyleCop in Visual Studio improves code quality and consistency by enforcing coding standards. Also, we saw how we can configure it to make sure it aligns with our team’s vision and the project’s needs. Overall, with the real-time feedback and build-time analysis StyleCop has to offer, we developers can have an easier way to maintain standardized coding, readability, and collaboration in our team.
Tested with .NET 10.0.10 (SDK 10.0.302) and StyleCop.Analyzers 1.1.118.









