Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

Overview of .NET source code analysis

  • 2024-11-12
Feedback

In this article

.NET compiler platform (Roslyn) analyzers inspect your C# or Visual Basic code for code quality and style issues. Starting in .NET 5, these analyzers are included with the .NET SDK and you don't need to install them separately. If your project targets .NET 5 or later, code analysis is enabled by default. If your project targets a different .NET implementation, for example, .NET Core, .NET Standard, or .NET Framework, you must manually enable code analysis by setting theEnableNETAnalyzers property totrue.

If you don't want to move to the .NET 5+ SDK, have a non-SDK-style .NET Framework project, or prefer a NuGet package-based model, the analyzers are also available in theMicrosoft.CodeAnalysis.NetAnalyzers NuGet package. You might prefer a package-based model for on-demand version updates.

Note

.NET analyzers are target-framework agnostic. That is, your project does not need to target a specific .NET implementation. The analyzers work for projects that target .NET 5+ as well as earlier .NET versions, such as .NET Core 3.1 and .NET Framework 4.7.2. However, to enable code analysis using theEnableNETAnalyzers property, your project must reference aproject SDK.

If rule violations are found by an analyzer, they're reported as a suggestion, warning, or error, depending on how each rule isconfigured. Code analysis violations appear with the prefix "CA" or "IDE" to differentiate them from compiler errors.

Code quality analysis

Code quality analysis ("CAxxxx") rules inspect your C# or Visual Basic code for security, performance, design and other issues. Analysis is enabled, by default, for projects that target .NET 5 or later. You can enable code analysis on projects that target earlier .NET versions by setting theEnableNETAnalyzers property totrue. You can also disable code analysis for your project by settingEnableNETAnalyzers tofalse.

Tip

If you're using Visual Studio, many analyzer rules have associatedcode fixes that you can apply to automatically correct the problem. Code fixes are shown in the light bulb icon menu.

Enabled rules

The following rules are enabled, by default, as errors or warnings in .NET 9. Additional rules are enabled as suggestions.

Diagnostic IDCategorySeverityVersion addedDescription
CA1416InteroperabilityWarning.NET 5Validate platform compatibility
CA1417InteroperabilityWarning.NET 5Do not useOutAttribute on string parameters for P/Invokes
CA1418InteroperabilityWarning.NET 6Use valid platform string
CA1420InteroperabilityWarning.NET 7Using features that require runtime marshalling when it's disabled will result in run-time exceptions
CA1422InteroperabilityWarning.NET 7Validate platform compatibility
CA1831PerformanceWarning.NET 5UseAsSpan instead of range-based indexers for string when appropriate
CA1856PerformanceError.NET 8Incorrect usage ofConstantExpected attribute
CA1857PerformanceWarning.NET 8A constant is expected for the parameter
CA2013ReliabilityWarning.NET 5Do not useReferenceEquals with value types
CA2014ReliabilityWarning.NET 5Do not usestackalloc in loops
CA2015ReliabilityWarning.NET 5Do not define finalizers for types derived fromMemoryManager<T>
CA2017ReliabilityWarning.NET 6Parameter count mismatch
CA2018ReliabilityWarning.NET 6Thecount argument toBuffer.BlockCopy should specify the number of bytes to copy
CA2021ReliabilityWarning.NET 8Do not callEnumerable.Cast<T> orEnumerable.OfType<T> with incompatible types
CA2022ReliabilityWarning.NET 9Avoid inexact read withStream.Read
CA2200UsageWarning.NET 5Rethrow to preserve stack details
CA2247UsageWarning.NET 5Argument passed toTaskCompletionSource constructor should beTaskCreationOptions enum instead ofTaskContinuationOptions
CA2252UsageError.NET 6Opt in to preview features
CA2255UsageWarning.NET 6TheModuleInitializer attribute should not be used in libraries
CA2256UsageWarning.NET 6All members declared in parent interfaces must have an implementation in aDynamicInterfaceCastableImplementation-attributed interface
CA2257UsageWarning.NET 6Members defined on an interface with theDynamicInterfaceCastableImplementationAttribute should bestatic
CA2258UsageWarning.NET 6Providing aDynamicInterfaceCastableImplementation interface in Visual Basic is unsupported
CA2259UsageWarning.NET 7ThreadStatic only affects static fields
CA2260UsageWarning.NET 7Use correct type parameter
CA2261UsageWarning.NET 8Do not useConfigureAwaitOptions.SuppressThrowing withTask<TResult>
CA2264UsageWarning.NET 9Do not pass a non-nullable value toArgumentNullException.ThrowIfNull
CA2265UsageWarning.NET 9Do not compareSpan<T> tonull ordefault

You can change the severity of these rules to disable them or elevate them to errors. You can alsoenable more rules.

Enable additional rules

Analysis mode refers to a predefined code analysis configuration where none, some, or all rules are enabled. In the default analysis mode (Default), only a small number of rules areenabled as build warnings. You can change the analysis mode for your project by setting the<AnalysisMode> property in the project file. The allowable values are:

ValueDescription
NoneAll rules are disabled. You can selectivelyopt in to individual rules to enable them.
DefaultDefault mode, where certain rules are enabled as build warnings, certain rules are enabled as Visual Studio IDE suggestions, and the remainder are disabled.
MinimumMore aggressive mode thanDefault mode. Certain suggestions that are highly recommended for build enforcement are enabled as build warnings. To see which rules this includes, inspect the%ProgramFiles%/dotnet/sdk/[version]/Sdks/Microsoft.NET.Sdk/analyzers/build/config/analysislevel_[level]_minimum.globalconfig file. (For .NET 7 and earlier versions, the file extension is.editorconfig.)
RecommendedMore aggressive mode thanMinimum mode, where more rules are enabled as build warnings. To see which rules this includes, inspect the%ProgramFiles%/dotnet/sdk/[version]/Sdks/Microsoft.NET.Sdk/analyzers/build/config/analysislevel_[level]_recommended.globalconfig file. (For .NET 7 and earlier versions, the file extension is.editorconfig.)
AllAll rules are enabled as build warnings*. You can selectivelyopt out of individual rules to disable them.

* The following rules arenot enabled by settingAnalysisMode toAll or by settingAnalysisLevel tolatest-all: CA1017, CA1045, CA1005, CA1014, CA1060, CA1021, and the code metrics analyzer rules (CA1501, CA1502, CA1505, CA1506, and CA1509). These legacy rules might be deprecated in a future version. However, you can still enable them individually using adotnet_diagnostic.CAxxxx.severity = <severity> entry.

You can also omit<AnalysisMode> in favor of a compound value for the<AnalysisLevel> property. For example, the following value enables the recommended set of rules for the latest release:<AnalysisLevel>latest-Recommended</AnalysisLevel>. For more information, seeAnalysisLevel.

To find the default severity for each available rule and whether or not the rule is enabled inDefault analysis mode, see thefull list of rules.

Treat warnings as errors

If you use the-warnaserror flag when you build your projects, all code analysis warnings are also treated as errors. If you do not want code quality warnings (CAxxxx) to be treated as errors in presence of-warnaserror, you can set theCodeAnalysisTreatWarningsAsErrors MSBuild property tofalse in your project file.

<PropertyGroup>  <CodeAnalysisTreatWarningsAsErrors>false</CodeAnalysisTreatWarningsAsErrors></PropertyGroup>

You'll still see any code analysis warnings, but they won't break your build.

Latest updates

By default, you'll get the latest code analysis rules and default rule severities as you upgrade to newer versions of the .NET SDK. If you don't want this behavior, for example, if you want to ensure that no new rules are enabled or disabled, you can override it in one of the following ways:

  • Set theAnalysisLevel MSBuild property to a specific value to lock the warnings to that set. When you upgrade to a newer SDK, you'll still get bug fixes for those warnings, but no new warnings will be enabled and no existing warnings will be disabled. For example, to lock the set of rules to those that ship with version 8.0 of the .NET SDK, add the following entry to your project file.

    <PropertyGroup>  <AnalysisLevel>8.0</AnalysisLevel></PropertyGroup>

    Tip

    The default value for theAnalysisLevel property islatest, which means you always get the latest code analysis rules as you move to newer versions of the .NET SDK.

    For more information, and to see a list of possible values, seeAnalysisLevel.

  • Install theMicrosoft.CodeAnalysis.NetAnalyzers NuGet package to decouple rule updates from .NET SDK updates. For projects that target .NET 5+, installing the package turns off the built-in SDK analyzers. You'll get a build warning if the SDK contains a newer analyzer assembly version than that of the NuGet package. To disable the warning, set the_SkipUpgradeNetAnalyzersNuGetWarning property totrue.

    Note

    If you install the Microsoft.CodeAnalysis.NetAnalyzers NuGet package, you should not add theEnableNETAnalyzers property to either your project file or aDirectory.Build.props file. When the NuGet package is installed and theEnableNETAnalyzers property is set totrue, a build warning is generated.

Code-style analysis

Code-style analysis ("IDExxxx") rules enable you to define and maintain consistent code style in your codebase. The default enablement settings are:

  • Command-line build: Code-style analysis isdisabled, by default, for all .NET projects on command-line builds.

    You canenable code-style analysis on build, both at the command line and inside Visual Studio. Code style violations appear as warnings or errors with an "IDE" prefix. This enables you to enforce consistent code styles at build time.

  • Visual Studio: Code-style analysis isenabled, by default, for all .NET projects inside Visual Studio ascode refactoring quick actions.

For a full list of code-style analysis rules, seeCode style rules.

Enable on build

You can enable code-style analysis when building from the command-line and in Visual Studio. (However, for performance reasons,a handful of code-style rules will still apply only in the Visual Studio IDE.)

Follow these steps to enable code-style analysis on build:

  1. Set the MSBuild propertyEnforceCodeStyleInBuild totrue.

  2. In an.editorconfig file,configure each "IDE" code style rule that you wish to run on build as a warning or an error. For example:

    [*.{cs,vb}]# IDE0040: Accessibility modifiers required (escalated to a build warning)dotnet_diagnostic.IDE0040.severity = warning

    Tip

    Starting in .NET 9, you can also use theoption format to specify a severity and have it be respected at build time. For example:

    [*.{cs,vb}]# IDE0040: Accessibility modifiers required (escalated to a build warning)dotnet_style_require_accessibility_modifiers = always:warning

    Alternatively, you can configure an entire category to be a warning or error, by default, and then selectively turn off rules in that category that you don't want to run on build. For example:

    [*.{cs,vb}]# Default severity for analyzer diagnostics with category 'Style' (escalated to build warnings)dotnet_analyzer_diagnostic.category-Style.severity = warning# IDE0040: Accessibility modifiers required (disabled on build)dotnet_diagnostic.IDE0040.severity = silent

Suppress a warning

One way to suppress a rule violation is to set the severity option for that rule ID tonone in an EditorConfig file. For example:

dotnet_diagnostic.CA1822.severity = none

For more information and other ways to suppress warnings, seeHow to suppress code analysis warnings.

Third-party analyzers

In addition to the official .NET analyzers, you can also install third party analyzers, such asStyleCop,Roslynator,XUnit Analyzers, andSonar Analyzer.

See also

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo