Анализ кода си шарп

Overview of .NET source code analysis

.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 the EnableNETAnalyzers property to true .

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 the Microsoft.CodeAnalysis.NetAnalyzers NuGet package. You might prefer a package-based model for on-demand version updates.

.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 the EnableNETAnalyzers property, your project must reference a project SDK.

If rule violations are found by an analyzer, they’re reported as a suggestion, warning, or error, depending on how each rule is configured. 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 the EnableNETAnalyzers property to true . You can also disable code analysis for your project by setting EnableNETAnalyzers to false .

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

Enabled rules

The following rules are enabled, by default, in .NET 7.

Diagnostic ID Category Severity Description
CA1416 Interoperability Warning Validate platform compatibility
CA1417 Interoperability Warning Do not use OutAttribute on string parameters for P/Invokes
CA1418 Interoperability Warning Use valid platform string
CA1420 Interoperability Warning Using features that require runtime marshalling when it’s disabled will result in run-time exceptions
CA1422 Interoperability Warning Validate platform compatibility
CA1831 Performance Warning Use AsSpan instead of range-based indexers for string when appropriate
CA2013 Reliability Warning Do not use ReferenceEquals with value types
CA2014 Reliability Warning Do not use stackalloc in loops
CA2015 Reliability Warning Do not define finalizers for types derived from MemoryManager
CA2017 Reliability Warning Parameter count mismatch
CA2018 Reliability Warning The count argument to Buffer.BlockCopy should specify the number of bytes to copy
CA2200 Usage Warning Rethrow to preserve stack details
CA2247 Usage Warning Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions
CA2252 Usage Error Opt in to preview features
CA2255 Usage Warning The ModuleInitializer attribute should not be used in libraries
CA2256 Usage Warning All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation -attributed interface
CA2257 Usage Warning Members defined on an interface with the DynamicInterfaceCastableImplementationAttribute should be static
CA2258 Usage Warning Providing a DynamicInterfaceCastableImplementation interface in Visual Basic is unsupported
CA2259 Usage Warning ThreadStatic only affects static fields
CA2260 Usage Warning Use correct type parameter
Читайте также:  Пример создания коллекции java

The following rules are enabled, by default, in .NET 6.

Diagnostic ID Category Severity Description
CA1416 Interoperability Warning Platform compatibility analyzer
CA1417 Interoperability Warning Do not use OutAttribute on string parameters for P/Invokes
CA1418 Interoperability Warning Use valid platform string
CA1831 Performance Warning Use AsSpan instead of range-based indexers for string when appropriate
CA2013 Reliability Warning Do not use ReferenceEquals with value types
CA2014 Reliability Warning Do not use stackalloc in loops
CA2015 Reliability Warning Do not define finalizers for types derived from MemoryManager
CA2017 Reliability Warning Parameter count mismatch
CA2018 Reliability Warning The count argument to Buffer.BlockCopy should specify the number of bytes to copy
CA2200 Usage Warning Rethrow to preserve stack details
CA2252 Usage Error Opt in to preview features
CA2247 Usage Warning Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions
CA2255 Usage Warning The ModuleInitializer attribute should not be used in libraries
CA2256 Usage Warning All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation -attributed interface
CA2257 Usage Warning Members defined on an interface with the DynamicInterfaceCastableImplementationAttribute should be static
CA2258 Usage Warning Providing a DynamicInterfaceCastableImplementation interface in Visual Basic is unsupported

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

  • For a list of rules that are included with each .NET SDK version, see Analyzer releases.
  • For a list of all the code quality rules, see Code quality 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 are enabled as build warnings. You can change the analysis mode for your project by setting the property in the project file. The allowable values are:

Читайте также:  Python loop lines in file
Value Description
None No rules are enabled.
Default The default set of rules are enabled. These rules are listed at Enabled rules.
Minimum More aggressive mode than Default mode. Certain suggestions that are highly recommended for build enforcement are enabled as build warnings. To see which rules this includes, inspect the analysislevel_[level]_minimum.editorconfig file in the %ProgramFiles%/dotnet/sdk/[version]/Sdks/Microsoft.NET.Sdk/analyzers/build/config directory.
Recommended More aggressive mode than the Minimum mode, where more rules are enabled as build warnings. To see which rules this includes, inspect the analysislevel_[level]_recommended.editorconfig file in the %ProgramFiles%/dotnet/sdk/[version]/Sdks/Microsoft.NET.Sdk/analyzers/build/config directory.
All All rules are enabled.

To find the default severity for each available rule and whether or not the rule is enabled in Default analysis mode, see the full 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 the CodeAnalysisTreatWarningsAsErrors MSBuild property to false in your project file.

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 the AnalysisLevel 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 5.0 of the .NET SDK, add the following entry to your project file.

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

Читайте также:  Defined php header 404

Note If you install the Microsoft.CodeAnalysis.NetAnalyzers NuGet package, you should not add the EnableNETAnalyzers property to either your project file or a Directory.Build.props file. When the NuGet package is installed and the EnableNETAnalyzers property is set to true , 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 is disabled, by default, for all .NET projects on command-line builds. Starting in .NET 5, you can enable 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 is enabled, by default, for all .NET projects inside Visual Studio as code refactoring quick actions.

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

Enable on build

With the .NET 5 SDK and later versions, 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 property EnforceCodeStyleInBuild to true .
  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:
[*.] # IDE0040: Accessibility modifiers required (escalated to a build warning) dotnet_diagnostic.IDE0040.severity = 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:

[*.] # 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 to none in an EditorConfig file. For example:

dotnet_diagnostic.CA1822.severity = none 

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

Run code analysis as a GitHub Action

The dotnet/code-analysis GitHub Action lets you run .NET code analyzers as part of continuous integration (CI) in an offline mode. For more information, see .NET code analysis GitHub Action.

Third-party analyzers

In addition to the official .NET analyzers, you can also install third party analyzers, such as StyleCop, Roslynator, XUnit Analyzers, and Sonar Analyzer.

See also

Источник

Оцените статью