Write Better Code Faster with Roslyn Analyzers
Roslyn, the .NET compiler platform, helps you catch bugs even before you run your code. One example is Roslyn’s spellcheck analyzer that is built into Visual Studio. Let’s say you are creating a static method and misspelled the word static as statc. You will be able to see this spelling error before you run your code because Roslyn can produce warnings in your code as you type even before you’ve finished the line. In other words, you don’t have to build your code to find out that you made a mistake.
Roslyn analyzers can also surface an automatic code fix through the Visual Studio light bulb icon that allows you to fix your code immediately.
But what if you could catch even more bugs?
Let me introduce you to Roslyn analyzer packages. These collections of analyzers provide a more verbose analysis, but don’t ship with the default Visual Studio tools. To learn more about our favorite Roslyn analyzers visit our Roslyn analyzers GitHub repository. This repository includes the FxCop rules that are still applicable to modern software development, but now target our modern code analysis platform based on Roslyn. Let’s go ahead and install this package to be more productive and write better code faster!
To Install FxCop analyzers as a NuGet package:
- Assuming you’re using Visual Studio 2017 Version 15.8 or newer, choose the most recent version of Microsoft.CodeAnalysis.FxCopAnalyzers.
- Install the package in Visual Studio, using the Package Manager UI.
Once you have the package installed you can simply customize the analyzer diagnostics from the Solution Explorer. An analyzer node will appear under the References or Dependencies node in the Solution Explorer. If you expand the analyzers, and then expand one of the analyzer assemblies, you can see all the diagnostics in the assembly.
You can view the properties of a diagnostic, including its description and default severity, in the properties window. To view the properties, right-click on the rule and select Properties, or select the rule and then press Alt+Enter.
The icons next to each diagnostic in Solution Explorer correspond to the icons you see in the rule set when you open it in the editor:
- the “i” in a circle indicates a severity of Info
- the “!” in a triangle indicates a severity of Warning
- the “x” in a circle indicates a severity of Error
- the “i” in a circle on a light-colored background indicates a severity of Hidden
- the “↓” in a circle indicates a suppressed diagnostic
You can then set the rule set severity from the Solution Explorer. In the Solution Explorer, expand Dependencies > Analyzers. Expand the assembly that contains the rule you want to set the severity for. Right-click on the rule and select Set Rule Set Severity and in the fly-out menu, select one of the severity options.
If you set the rule severity to a warning you will then receive a warning in your code for that specific rule set.
Now that you understand how analyzers work you can be more productive and write better code faster!
Q: This warning appears in Visual Studio: “Run Code Analysis has been deprecated in favor of FxCop analyzers, which run during build. Refer to https://aka.ms/fxcopanalyzers to migrate to FxCop analyzers”. What does this mean? A: FxCop is the Code Analysis engine that predates Roslyn by almost a decade. Just like we moved our compiler forward (e.g. introduced Roslyn), we are also moving our code analysis technology forward to the Roslyn platform. Since it is powered by the .NET Compiler Platform it can produce warnings in your code as you type. In other words, you don’t have to build your code to find out that you made a mistake.
Q: What’s the difference between FxCop analyzers and legacy FxCop? A: FxCop analyzers analyze source code in real time and during compilation, whereas legacy FxCop is a static code analysis and analyzes binary files after build has completed. For more information, see Roslyn analyzers vs. static code analysis and FxCop analyzers FAQ.
Q: Can I write custom analyzers? A: Absolutely! Documentation on how to write an analyzer is found here.
Q: Should I use Roslyn analyzers or .editorconfig for code style? A: Roslyn analyzers and .editorconfig files work hand-in-hand. When you define code styles in an .editorconfig file or on the text editor options page, you’re actually configuring the Roslyn analyzers that are built into Visual Studio.
Q: Do analyzers work in continuous integration (CI) builds? A: Yes, analyzers installed as NuGet packages can be enforced in CI builds.
Q: Where can I request more analyzers or report bugs? A: You can request more analyzer and report bugs on the Roslyn repository on GitHub.
If you want to write your first analyzer, you can check my step-by-step guide: Writing a Roslyn analyzer. It also cover how to publish the analyzer.
Could you expand on how to enforce analysers in CI builds please? I can run them, and and diagnostics appear in the logs, but I’ve yet to find a way to surface those diagnostics in e.g. TeamCity or Bamboo, or have the build fail if there are diagnostics, etc.
I guess you simply Set Rule Set Severity as mentioned in the article to Error and it will fail the build process
You can create the problems as warnings for developers in Debug profile, and set “treat warnings as errors” for your CI using Release profile. In this way devs can debug the code even if it not perfect, but all warnings must be fixed eventually before checking in or releasing the code.
I don’t remember the exact details how to do it but I have done it many times in the past. If I remember right, “TreatWarningsAsErrors” can be set in the project file.
Hey what is the difference between ready to start platform like https://info.migrateto.net/dazzle-lite-framework and this one?
Is it possible to enable code analysis globally for all solutions?
Hi Florian! If you install analyzers as a Visual Studio extension (VSIX), they apply at the solution level, to all instances of Visual Studio. If you install the analyzers as a NuGet package, they apply only to the project where the NuGet package was installed. More info on this is found here.
If you don’t want to go the extension route (ie: you want everyone on the project to use the same analyzers), I have found helpful to have a .props file that I can include in all my project with one line in the csproj that imports that file. I use that file to setup analyzers, highest warnings, treat warnings as errors, etc. I think you can also just name the file “Directory.Build.props” and it will be automatically included without you having to include <Include> in your csproj files, but I’ve never tried that
Some time ago I wrote an article about using Roslyn too, but I wrote about the development of standalone static code analyzers. Anyway, it contains some base concepts of working with Roslyn and analyzers development. You can read an article here: Introduction to Roslyn and its use in program development
Maybe it will be useful for someone. 🙂
I’m skeptic about the practical value of most of the rules beyond the basic ones already included in VS2019. Even some of the “standard” rules are too intrusive, because most of them are based in local information. A classical example: introduce a default implementation for an interface in a precurssor class that still doesn’t implement the interface. You’ll inmediatly have a rule complaining about “unused parameter”… just because the rule doesn’t looks beyond the current class to find the reason for writing the method.
Could anyone please clarify what the difference is between https://github.com/dotnet/roslyn-analyzers and https://github.com/DotNetAnalyzers/StyleCopAnalyzers? Are these both MS staffed project teams or is the former MS and the later community-driven? Is one a sub-set or super-set of the other? Does anyone have any insight on which is preferable? This would appear to be a happy problem of being spilt for choice.
Hi Simon! StyleCop analyzers is a non-Microsoft open source project and has all the style based syntactic analyzers for code style preferences. Roslyn analyzers is a Microsoft open source project and has Microsoft’s most recommended code quality analyzers.
For the last question in your FAQ, I think the correct repository for features/bugs is https://github.com/dotnet/roslyn-analyzers/issues
During my CI builds, I have the legacy FxCop configured to a standard ruleset to avoid unapproved changes to rules in the project. Can this be accomplished in this new analyzer?