How to enable the built-in .NET Analyzers

.NET Analyzers (which replaces FxCop) ships with the .NET 5 SDK. If you have the .NET 5 SDK installed, then you can enable .NET Analyzers by adding properties to the .csproj file. You can use this even if your project isn’t targeting .NET 5. If you don’t have the .NET 5 SDK installed, but want to use .NET Analyzers, you can install it with a nuget package.

In this article, I’ll show both ways to enable .NET Analyzers and then show a simple way to verify that it’s working.

If you .NET 5 SDK installed

If you have the .NET 5 SDK installed, you can enable the built-in .NET Analyzers by adding the following properties to the .csproj file:

<PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> <EnableNETAnalyzers>true</EnableNETAnalyzers> <AnalysisMode>AllEnabledByDefault</AnalysisMode> <AnalysisLevel>latest</AnalysisLevel> </PropertyGroup>
Code language: HTML, XML (xml)

I had to add the AnalysisLevel property to the .csproj explicitly to get it working. The project properties Code Analysis tab shows an “Analysis Level” setting, but it doesn’t seem to work (this is probably a bug in VS2019 16.8). Explicitly putting the setting in the .csproj file made it work though.

I recommend using AnalysisMode=AllEnabledByDefault at first, and then turning off individual rules you don’t want as they come up.

Note: You can use the analyzer from the .NET 5 SDK even if your project isn’t targeting .NET 5.

If you don’t have the .NET 5 SDK installed

Since you don’t have the .NET 5 SDK installed, but want the .NET Analyzers, you can install the nuget package:

Install-Package Microsoft.CodeAnalysis.NetAnalyzers
Code language: PowerShell (powershell)

Then add the following settings to the .csproj file:

<PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp3.1</TargetFramework> <AnalysisMode>AllEnabledByDefault</AnalysisMode> <AnalysisLevel>latest</AnalysisLevel> </PropertyGroup>
Code language: HTML, XML (xml)

Note: Since I have .NET 5 SDK installed, I’m not 100% sure if this is all you need to do to get it working. If you are going this route, and it doesn’t work, please leave a comment.

Check if code analysis works

After enabling .NET Analyzers, you can check if it’s working by intentionally adding code that will trigger a code analysis warning, such as the following enum:

public enum Animals { Dog = 1, Cat = 2 }
Code language: C# (cs)

If in doubt, rebuild the project. If everything is working as intended, then you should see the following code analysis warning:

CA1008 Add a member to Animals that has a value of zero with a suggested name of ‘None’

Leave a Comment