« Code analysis » : différence entre les versions

De Banane Atomic
Aller à la navigationAller à la recherche
 
(38 versions intermédiaires par le même utilisateur non affichées)
Ligne 36 : Ligne 36 :
[*.cs]
[*.cs]
indent_size              = 4
indent_size              = 4
tab_width                = 4
trim_trailing_whitespace = true
trim_trailing_whitespace = true
</filebox>
</filebox>
Ligne 45 : Ligne 46 :
</filebox>
</filebox>


== Miscellaneous configuration ==
== Formatting configuration ==
<filebox fn='.editorconfig' lang='ini'>
<filebox fn='.editorconfig' lang='ini'>
# IDE0055 Formatting rule
# Sort using and Import directives with System.* appearing first
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true
dotnet_sort_system_directives_first = true
</filebox>
== Code Quality configuration ==
<filebox fn='.editorconfig' lang='ini'>
# Identifiers should have correct prefix
dotnet_code_quality.CA1715.exclude_single_letter_type_parameters = true
# Use property instead of Linq Enumerable method
# Exclude FirstOrDefault and LastOrDefault methods
dotnet_code_quality.CA1826.exclude_ordefault_methods = true
# Do not directly await a Task
# only apply this rule to code that produces a console application or a dynamically linked library
dotnet_code_quality.CA2007.output_kind = ConsoleApplication, DynamicallyLinkedLibrary
</filebox>
</filebox>


== Style configuration ==
== Style configuration ==
<filebox fn='.editorconfig' lang='ini'>
<filebox fn='.editorconfig' lang='ini'>
# IDE0160 / IDE0161: Namespace declaration preferences
csharp_style_namespace_declarations = file_scoped : error
# IDE0007 / IDE0008: 'var' preferences
# IDE0007 / IDE0008: 'var' preferences
csharp_style_var_for_built_in_types    = true
csharp_style_var_for_built_in_types    = true
csharp_style_var_when_type_is_apparent = true
csharp_style_var_when_type_is_apparent = true
csharp_style_var_elsewhere            = false : suggestion
csharp_style_var_elsewhere            = true
 
# IDE0011: Add braces
csharp_prefer_braces = when_multiline
 
# IDE0022: Use expression body for methods
csharp_style_expression_bodied_methods = when_on_single_line
 
# IDE0047 and IDE0048: Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary
 
# IDE0061: Use expression body for local functions
csharp_style_expression_bodied_local_functions = when_on_single_line
 
# IDE0160 / IDE0161: Namespace declaration preferences
csharp_style_namespace_declarations = file_scoped
</filebox>
</filebox>


Ligne 67 : Ligne 95 :
dotnet_diagnostic.VSSpell001.severity = suggestion
dotnet_diagnostic.VSSpell001.severity = suggestion
dotnet_diagnostic.VSSpell002.severity = suggestion
dotnet_diagnostic.VSSpell002.severity = suggestion
# Implement standard exception constructors
dotnet_diagnostic.CA1032.severity = none


# Specify CultureInfo
# Specify CultureInfo
dotnet_diagnostic.CA1304.severity = suggestion
dotnet_diagnostic.CA1304.severity = suggestion
# Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = suggestion
# Specify StringComparison for clarity
dotnet_diagnostic.CA1307.severity = suggestion
# Specify StringComparison for correctness
dotnet_diagnostic.CA1310.severity = suggestion
# Specify a culture
# Specify a culture
dotnet_diagnostic.CA1311.severity = suggestion
dotnet_diagnostic.CA1311.severity = suggestion
# Do not directly await a Task (Add ConfigureAwait(false) while awaiting tasks)
dotnet_diagnostic.CA2007.severity = none
# The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
# Auto-generated code requires an explicit '#nullable' directive in source.
dotnet_diagnostic.CS8669.severity = none
# Remove unnecessary expression value
dotnet_diagnostic.IDE0058.severity = none
# For unit tests
# Identifiers should not contain underscores
dotnet_diagnostic.CA1707.severity = none
</filebox>
</filebox>


== Custom naming convention rules ==
== Custom naming style rules ==
<filebox fn='.editorconfig' lang='ini'>
<filebox fn='.editorconfig' lang='ini'>
# Style Definitions
# Style Definitions
Ligne 132 : Ligne 183 :
! Fixer
! Fixer
! Description
! Description
|-
| Apply object creation preferences ||
|-
| Remove unused variables ||
|-
| Apply IsNot preferences ||
|-
| Remove unnecessary imports or usings ||
|-
|-
| Apply conditional expression preferences || apply ternary conditional expression {{boxx|? :}}
| Apply conditional expression preferences || apply ternary conditional expression {{boxx|? :}}
|-
| Apply auto property preferences ||
|-
|-
| Apply statement after block preferences (experimental) ||  
| Apply statement after block preferences (experimental) ||  
|-
| Apply parentheses preferences ||
|-
| Apply object/collection initialization preferences || initialize properties while creating a new object
|-
| Add 'this' or 'Me' qualification ||
|-
| Apply coalesce expression preferences || {{boxx|??}}
|-
| Fix all warnings and errors set in EditorConfig ||
|-
|-
| Apply compound assignment preferences ||  
| Apply compound assignment preferences ||  
Ligne 143 : Ligne 214 :
| Add accessibility modifiers ||  
| Add accessibility modifiers ||  
|-
|-
| Apply unused value preferences ||  
| Apply file header preferences ||
|-
| Apply unused value preferences || {{boxx|1=_ = SomeMethod();}}
|-
|-
| Apply namespace matches folder preferences ||  
| Apply namespace matches folder preferences ||  
Ligne 168 : Ligne 241 :
|-
|-
| Apply string interpolation preferences ||  
| Apply string interpolation preferences ||  
|-
| Sort imports or usings ||
|-
|-
| Apply language/framework type preferences ||  
| Apply language/framework type preferences ||  
Ligne 175 : Ligne 250 :
| Apply null checking preferences ||  
| Apply null checking preferences ||  
|-
|-
| Apply expression/block body preferences ||  
| Format document || add missing spaces, remove extra spaces
|-
|-
| Apply 'readonly struct' preferences ||  
| Apply expression/block body preferences || {{boxx|1==>}}
|-
| Apply 'readonly struct' preferences || use switch expression, combine {{boxx|if}} condition with {{boxx|is}} {{boxx|and}} {{boxx|or}}
|-
|-
| Apply pattern matching preferences ||  
| Apply pattern matching preferences ||  
Ligne 195 : Ligne 272 :
| Remove unnecessary nullable directives ||  
| Remove unnecessary nullable directives ||  
|-
|-
| Apply method group convertion preferences ||  
| Apply method group conversion preferences ||  
|-
|-
| Apply conditional expression preferences ||  
| Apply static local function preferences ||  
|-
|-
| Apply conditional expression preferences ||  
| Apply throw expression preferences ||  
|-
|-
| Apply conditional expression preferences ||  
| Apply deconstruct preferences ||  
|-
|-
| Apply conditional expression preferences ||  
| Add required braces for single-line control statements ||
|-
| Apply default(T) preferences ||
|-
| Apply new preferences ||
|-
| Apply conditional delegate call preferences ||
|-
| Apply using statement preferences ||
|-
| Apply namespace preferences ||
|-
| Apply local over anonymous function preferences ||  
|}
|}
{{info | Fixers that may cause problems:
* Apply conditional expression preferences: not always readable
* Fix all warnings and errors set in EditorConfig
* Apply unused value preferences: useless {{boxx|1=_ =}}
* Fix analyzer warnings and errors set in EditorConfig
* Apply expression/block body preferences
* Add required braces for single-line control statements}}

Dernière version du 16 juin 2024 à 12:57

Links

Enable additional rules

Those rules are enabled by default.
Edit the project file to enable additional rules:

MyProject.csproj
<PropertyGroup>
  <!-- ... -->
  <AnalysisLevel>latest-recommended</AnalysisLevel>
</PropertyGroup>

Editorconfig

Core options

.editorconfig
root = true

# All files
[*]
indent_style         = space
insert_final_newline = true
charset              = utf-8

# XML project files
[*.csproj]
indent_size = 2

# JSON config files
[*.json]
indent_size = 2

# C# code files
[*.cs]
indent_size              = 4
tab_width                = 4
trim_trailing_whitespace = true

Analyzer configuration

.editorconfig
# set the rules severity to warning
dotnet_analyzer_diagnostic.severity = warning

Formatting configuration

.editorconfig
# IDE0055 Formatting rule
# Sort using and Import directives with System.* appearing first
dotnet_sort_system_directives_first = true

Code Quality configuration

.editorconfig
# Identifiers should have correct prefix
dotnet_code_quality.CA1715.exclude_single_letter_type_parameters = true

# Use property instead of Linq Enumerable method
# Exclude FirstOrDefault and LastOrDefault methods
dotnet_code_quality.CA1826.exclude_ordefault_methods = true

# Do not directly await a Task
# only apply this rule to code that produces a console application or a dynamically linked library
dotnet_code_quality.CA2007.output_kind = ConsoleApplication, DynamicallyLinkedLibrary

Style configuration

.editorconfig
# IDE0007 / IDE0008: 'var' preferences
csharp_style_var_for_built_in_types    = true
csharp_style_var_when_type_is_apparent = true
csharp_style_var_elsewhere             = true

# IDE0011: Add braces
csharp_prefer_braces = when_multiline

# IDE0022: Use expression body for methods
csharp_style_expression_bodied_methods = when_on_single_line

# IDE0047 and IDE0048: Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary

# IDE0061: Use expression body for local functions
csharp_style_expression_bodied_local_functions = when_on_single_line

# IDE0160 / IDE0161: Namespace declaration preferences
csharp_style_namespace_declarations = file_scoped

Disable rules

.editorconfig
# lower speller rule severity to suggestion
dotnet_diagnostic.VSSpell001.severity = suggestion
dotnet_diagnostic.VSSpell002.severity = suggestion

# Implement standard exception constructors
dotnet_diagnostic.CA1032.severity = none

# Specify CultureInfo
dotnet_diagnostic.CA1304.severity = suggestion
# Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = suggestion
# Specify StringComparison for clarity
dotnet_diagnostic.CA1307.severity = suggestion
# Specify StringComparison for correctness
dotnet_diagnostic.CA1310.severity = suggestion
# Specify a culture
dotnet_diagnostic.CA1311.severity = suggestion

# Do not directly await a Task (Add ConfigureAwait(false) while awaiting tasks)
dotnet_diagnostic.CA2007.severity = none

# The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.
# Auto-generated code requires an explicit '#nullable' directive in source.
dotnet_diagnostic.CS8669.severity = none

# Remove unnecessary expression value
dotnet_diagnostic.IDE0058.severity = none

# For unit tests
# Identifiers should not contain underscores
dotnet_diagnostic.CA1707.severity = none

Custom naming style rules

.editorconfig
# Style Definitions
dotnet_naming_style.upper_case_style.capitalization      = all_upper
dotnet_naming_style.camel_case_style.capitalization      = camel_case
dotnet_naming_style.end_with_async_style.required_suffix = Async
dotnet_naming_style.end_with_async_style.capitalization  = pascal_case

# Use UPPER_CASE for constant fields
dotnet_naming_symbols.constant_field_symbol.applicable_kinds     = field
dotnet_naming_symbols.constant_field_symbol.required_modifiers   = const
dotnet_naming_rule.constant_fields_should_be_upper_case.symbols  = constant_field_symbol
dotnet_naming_rule.constant_fields_should_be_upper_case.style    = upper_case_style
dotnet_naming_rule.constant_fields_should_be_upper_case.severity = warning

# Use camelCase for local variables, parameters, instance fields
dotnet_naming_symbols.local_parameter_field_symbol.applicable_kinds = local, parameter, field
dotnet_naming_rule.should_be_camel_case.symbols                     = local_parameter_field_symbol
dotnet_naming_rule.should_be_camel_case.style                       = camel_case_style
dotnet_naming_rule.should_be_camel_case.severity                    = warning

# Async methods should have "Async" suffix
dotnet_naming_symbols.async_method_symbol.applicable_kinds   = method
dotnet_naming_symbols.async_method_symbol.required_modifiers = async
dotnet_naming_rule.should_end_with_async.symbols             = async_method_symbol
dotnet_naming_rule.should_end_with_async.style               = end_with_async_style
dotnet_naming_rule.should_end_with_async.severity            = warning

Sonar Lint

.editorconfig
# S1135: Track uses of "TODO" tags
dotnet_diagnostic.S1135.severity = none

Installation

  • Installation the extension for Visual Studio or VS Code

Visual Studio

Change Code Style rules and generate a .editorconfig file

Tools → Options → Text Editor → C# → Code Style → General

Set the scope of live code analysis

  1. Tools → Options
  2. Text Editor → C# → Advanced
    1. Run background code analysis for: Current document
    2. Show compiler errors and warnings for: Open documents

Code Cleanup

Right click on the solution → Analyze and Code Cleanup:

  • Run Code Cleanup (Profile X)
  • Configure Code Cleanup (configure the profiles)
  • Set Analysis scope → Entire solution
Fixer Description
Apply object creation preferences
Remove unused variables
Apply IsNot preferences
Remove unnecessary imports or usings
Apply conditional expression preferences apply ternary conditional expression ? :
Apply auto property preferences
Apply statement after block preferences (experimental)
Apply parentheses preferences
Apply object/collection initialization preferences initialize properties while creating a new object
Add 'this' or 'Me' qualification
Apply coalesce expression preferences ??
Fix all warnings and errors set in EditorConfig
Apply compound assignment preferences
Removed unused parameters
Add accessibility modifiers
Apply file header preferences
Apply unused value preferences _ = SomeMethod();
Apply namespace matches folder preferences
Remove unnecessary casts
Make fields readonly
Remove unused suppressions
Fix analyzer warnings and errors set in EditorConfig
Apply inferred anonymous type member names preferences
Apply null propagation preferences
Apply using directive placement preferences
Apply tuple name preferences
Apply blank line preferences (experimental)
Order modifiers
Apply string interpolation preferences
Sort imports or usings
Apply language/framework type preferences
Apply simplify boolean expression preferences
Apply null checking preferences
Format document add missing spaces, remove extra spaces
Apply expression/block body preferences =>
Apply 'readonly struct' preferences use switch expression, combine if condition with is and or
Apply pattern matching preferences
Apply blank line between consecutive braces preferences (experimental)
Apply inline 'out' variable preferences
Apply blank line after colon in constructor initializer preferences (experimental)
Apply 'var' preferences
Apply range preferences
Apply embedded statement on same line preferences (experimental)
Remove unnecessary nullable directives
Apply method group conversion preferences
Apply static local function preferences
Apply throw expression preferences
Apply deconstruct preferences
Add required braces for single-line control statements
Apply default(T) preferences
Apply new preferences
Apply conditional delegate call preferences
Apply using statement preferences
Apply namespace preferences
Apply local over anonymous function preferences
Fixers that may cause problems:
  • Apply conditional expression preferences: not always readable
  • Fix all warnings and errors set in EditorConfig
  • Apply unused value preferences: useless _ =
  • Fix analyzer warnings and errors set in EditorConfig
  • Apply expression/block body preferences
  • Add required braces for single-line control statements