Previously you had to install and enable .NET Analyzers if you wanted to use it. Now, when you create a new project, it’s already installed and enabled by default (but you may want to change its settings). There are two main scenarios:
- .NET Analyzers is already installed and you want to change its settings.
- You want to install .NET Analyzers in an existing project.
If .NET Analyzers is already installed
When you create a new project targeting the latest .NET version, .NET Analyzers is automatically added to your project. You can see this in the Project > Dependencies > Analyzers tab in Visual Studio:
You can toggle .NET Analyzers off/on with the EnableNETAnalyzers setting in .csproj (or in a props file). You can also set the AnalysisMode and AnalysisLevel. Here’s an example:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
Code language: HTML, XML (xml)
Note: You may be able to control these settings in the Code Analysis tab in Visual Studio. I couldn’t get that working. Putting the settings in csproj made it work, so I kept using this approach.
Furthermore, I recommend starting with AnalysisMode=AllEnabledByDefault. Then as you run into analysis warnings you don’t want, you can disable them individually.
Note: You can use the analyzer from the .NET SDK even if your project isn’t targeting the latest .NET version.
Installing .NET Analyzers
If your project doesn’t already have .NET Analyzers installed, you can get it by installing the package:
Install-Package Microsoft.CodeAnalysis.NetAnalyzers
Code language: PowerShell (powershell)
Then add the following settings to the .csproj file to enable and configure it:
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>
Code language: HTML, XML (xml)
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)
Read more about another code analysis warning – CA2208: Instantiate argument exceptions correctly.
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’
Comments are closed.