diff --git a/Sources/Kysect.Configuin.Tests/EditorConfig/EditorConfigFormatterTests.cs b/Sources/Kysect.Configuin.Tests/EditorConfig/EditorConfigFormatterTests.cs index 712d5e4..f71a361 100644 --- a/Sources/Kysect.Configuin.Tests/EditorConfig/EditorConfigFormatterTests.cs +++ b/Sources/Kysect.Configuin.Tests/EditorConfig/EditorConfigFormatterTests.cs @@ -79,13 +79,22 @@ public void Format_QualityAndStyleRulesMashed_ReturnOrderedLinesWithHeader() public void FormatAccordingToRuleDefinitions_Sample_ReturnExpectedFormatterDocument() { string input = File.ReadAllText(Path.Combine("Resources", "Editor-config-sample.ini")); - string expected = File.ReadAllText(Path.Combine("Resources", "Editor-config-sample-formatted.ini")); + // TODO: Do smth with this =_= + string expected = File.ReadAllText(Path.Combine("Resources", "Editor-config-sample-formatted.ini")) + .Replace("\r\n", "\n") + .Replace("\n", Environment.NewLine); + ; MsLearnDocumentationRawInfo msLearnDocumentationRawInfo = _repositoryPathReader.Provide(Constants.GetPathToMsDocsRoot()); RoslynRules roslynRules = _msLearnDocumentationParser.Parse(msLearnDocumentationRawInfo); EditorConfigDocument editorConfigDocument = _parser.Parse(input); EditorConfigDocument formattedDocument = _formatter.FormatAccordingToRuleDefinitions(editorConfigDocument, roslynRules); - formattedDocument.ToFullString().Should().Be(expected); + // TODO: Do smth with this =_= + + formattedDocument.ToFullString() + .Replace("\r\n", "\n") + .Replace("\n", Environment.NewLine) + .Should().Be(expected); } private void FormatAndCompare(string input, string expected) diff --git a/Sources/Kysect.Configuin.Tests/Resources/Editor-config-sample-formatted.ini b/Sources/Kysect.Configuin.Tests/Resources/Editor-config-sample-formatted.ini index d4faf40..41e56e0 100644 --- a/Sources/Kysect.Configuin.Tests/Resources/Editor-config-sample-formatted.ini +++ b/Sources/Kysect.Configuin.Tests/Resources/Editor-config-sample-formatted.ini @@ -1,563 +1,4373 @@ -# https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/style-rules/language-rules - -[*.{cs,vb}] +[*] tab_width = 4 indent_size = 4 -end_of_line = crlf +indent_style = space +insert_final_newline = false -[*.cs] +[*.{xml,csproj,props}] +tab_width = 2 +indent_size = 2 -# IDE1006 -dotnet_diagnostic.IDE1006.severity = warning - -# camel_case_style - Define the camelCase style -dotnet_naming_style.camel_case_style.capitalization = camel_case -# pascal_case_style - Define the PascalCase style -dotnet_naming_style.pascal_case_style.capitalization = pascal_case -# first_upper_style - The first character must start with an upper-case character -dotnet_naming_style.first_upper_style.capitalization = first_word_upper -# prefix_interface_with_i_style - Interfaces must be PascalCase and the first character of an interface must be an 'I' -dotnet_naming_style.prefix_interface_with_i_style.capitalization = pascal_case -dotnet_naming_style.prefix_interface_with_i_style.required_prefix = I -# prefix_type_parameters_with_t_style - Generic Type Parameters must be PascalCase and the first character must be a 'T' -dotnet_naming_style.prefix_type_parameters_with_t_style.capitalization = pascal_case -dotnet_naming_style.prefix_type_parameters_with_t_style.required_prefix = T -# disallowed_style - Anything that has this style applied is marked as disallowed -dotnet_naming_style.disallowed_style.capitalization = pascal_case -dotnet_naming_style.disallowed_style.required_prefix = ____RULE_VIOLATION____ -dotnet_naming_style.disallowed_style.required_suffix = ____RULE_VIOLATION____ -# internal_error_style - This style should never occur... if it does, it indicates a bug in file or in the parser using the file -dotnet_naming_style.internal_error_style.capitalization = pascal_case -dotnet_naming_style.internal_error_style.required_prefix = ____INTERNAL_ERROR____ -dotnet_naming_style.internal_error_style.required_suffix = ____INTERNAL_ERROR____ - -dotnet_naming_symbols.public_protected_constant_fields_group.applicable_accessibilities = public, protected, protected_internal -dotnet_naming_symbols.public_protected_constant_fields_group.required_modifiers = const -dotnet_naming_symbols.public_protected_constant_fields_group.applicable_kinds = field -dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.symbols = public_protected_constant_fields_group -dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.style = pascal_case_style -dotnet_naming_rule.public_protected_constant_fields_must_be_pascal_case_rule.severity = warning - -dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_accessibilities = public, protected, protected_internal -dotnet_naming_symbols.public_protected_static_readonly_fields_group.required_modifiers = static, readonly -dotnet_naming_symbols.public_protected_static_readonly_fields_group.applicable_kinds = field -dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.symbols = public_protected_static_readonly_fields_group -dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.style = pascal_case_style -dotnet_naming_rule.public_protected_static_readonly_fields_must_be_pascal_case_rule.severity = warning - -dotnet_naming_symbols.other_public_protected_fields_group.applicable_accessibilities = public, protected, protected_internal -dotnet_naming_symbols.other_public_protected_fields_group.applicable_kinds = field -dotnet_naming_rule.other_public_protected_fields_disallowed_rule.symbols = other_public_protected_fields_group -dotnet_naming_rule.other_public_protected_fields_disallowed_rule.style = disallowed_style -dotnet_naming_rule.other_public_protected_fields_disallowed_rule.severity = error +[*.{cs,vb}] + +## csharp_style_pattern_matching_over_as_with_null_check +## - true - Prefer pattern matching over as expression with null-conditional member access. +## - false - Disables the rule. +csharp_style_pattern_matching_over_as_with_null_check = true +dotnet_code_quality.CA1062.null_check_validation_methods = ThrowIfNull +dotnet_code_quality.dispose_ownership_transfer_at_constructor = true # Autogenerated values [*.cs] ### IDE ### - +## Simplify name (IDE0001) +## This rule concerns the use of simplified type names in declarations and executable code, when possible. You can remove unnecessary name qualification to simplify code and improve readability. +## using System.IO; +## class C +## { +## // IDE0001: 'System.IO.FileInfo' can be simplified to 'FileInfo' +## System.IO.FileInfo file; +## +## // Fixed code +## FileInfo file; +## } dotnet_diagnostic.IDE0001.severity = warning -dotnet_diagnostic.IDE0002.severity = warning +## Simplify member access (IDE0002) +## This rule concerns use of simplified type member access in declarations and executable code, when possible. Unnecessary qualification can be removed to simplify code and improve readability. +## static void M1() { } +## static void M2() +## { +## // IDE0002: 'C.M1' can be simplified to 'M1' +## C.M1(); +## +## // Fixed code +## M1(); +## } +dotnet_diagnostic.IDE0002.severity = warning -# IDE0003 and IDE0009 +## Remove this or Me qualification (IDE0003) +## Add this or Me qualification (IDE0009) +## These two rules define whether or not you prefer the use of this (C#) and Me. (Visual Basic) qualifiers. To enforce that the qualifiers aren't present, set the severity of IDE0003 to warning or error. To enforce that the qualifiers are present, set the severity of IDE0009 to warning or error. +## For example, if you prefer qualifiers for fields and properties but not for methods or events, then you can enable IDE0009 and set the options dotnet_style_qualification_for_field and dotnet_style_qualification_for_property to true. However, this configuration would not flag methods and events that do have this and Me qualifiers. To also enforce that methods and events don't have qualifiers, enable IDE0003. dotnet_diagnostic.IDE0003.severity = warning -dotnet_diagnostic.IDE0009.severity = warning -dotnet_style_qualification_for_field = false:warning -dotnet_style_qualification_for_property = false:warning -dotnet_style_qualification_for_method = false:warning -dotnet_style_qualification_for_event = false:warning +dotnet_diagnostic.IDE0009.severity = none + +## Options: +## dotnet_style_qualification_for_field +## - true - Prefer fields to be prefaced with this. in C# or Me. in Visual Basic +## - false - Prefer fields not to be prefaced with this. or Me. +## // dotnet_style_qualification_for_field = true +## this.capacity = 0; +## +## // dotnet_style_qualification_for_field = false +## capacity = 0; +dotnet_style_qualification_for_field = false + +## dotnet_style_qualification_for_property +## - true - Prefer properties to be prefaced with this. in C# or Me. in Visual Basic. +## - false - Prefer properties not to be prefaced with this. or Me.. +## // dotnet_style_qualification_for_property = true +## this.ID = 0; +## +## // dotnet_style_qualification_for_property = false +## ID = 0; +dotnet_style_qualification_for_property = false + +## dotnet_style_qualification_for_method +## - true - Prefer methods to be prefaced with this. in C# or Me. in Visual Basic. +## - false - Prefer methods not to be prefaced with this. or Me.. +## // dotnet_style_qualification_for_method = true +## this.Display(); +## +## // dotnet_style_qualification_for_method = false +## Display(); +dotnet_style_qualification_for_method = false +## dotnet_style_qualification_for_event +## - true - Prefer events to be prefaced with this. in C# or Me. in Visual Basic. +## - false - Prefer events not to be prefaced with this. or Me.. +## // dotnet_style_qualification_for_event = true +## this.Elapsed += Handler; +## +## // dotnet_style_qualification_for_event = false +## Elapsed += Handler; +dotnet_style_qualification_for_event = false + +## Remove unnecessary cast (IDE0004) +## This rule flags unnecessary type casts. A cast expression is unnecessary if the code semantics would be identical with or without it. +## // Code with violations +## int v = (int)0; +## +## // Fixed code +## int v = 0; dotnet_diagnostic.IDE0004.severity = warning + +## Remove unnecessary import (IDE0005) +## This rule flags the following unnecessary constructs. If unnecessary, these constructs can be removed without changing the semantics of the code: +## using directives (C#). +## Import statements (Visual Basic). +## [!NOTE] +## To enable this rule on build, you need to enable XML documentation comments for the project. For more information, see dotnet/roslyn issue 41640. +## // Code with violations +## using System; +## using System.IO; // IDE0005: Using directive is unnecessary +## class C +## { +## public static void M() +## { +## Console.WriteLine("Hello"); +## } +## } +## +## // Fixed code +## using System; +## class C +## { +## public static void M() +## { +## Console.WriteLine("Hello"); +## } +## } dotnet_diagnostic.IDE0005.severity = warning -# IDE0007 and IDE0008 -dotnet_diagnostic.IDE0007.severity = warning -dotnet_diagnostic.IDE0008.severity = warning -csharp_style_var_for_built_in_types = false:silent -csharp_style_var_when_type_is_apparent = true:warning -csharp_style_var_elsewhere = false:silent +## Use var instead of explicit type (IDE0007) +## Use explicit type instead of var (IDE0008) +## These two style rules define whether the var keyword or an explicit type should be used in a variable declaration. To enforce that var is used, set the severity of IDE0007 to warning or error. To enforce that the explicit type is used, set the severity of IDE0008 to warning or error. +dotnet_diagnostic.IDE0007.severity = suggestion +dotnet_diagnostic.IDE0008.severity = suggestion + +## Options: +## csharp_style_var_for_built_in_types +## - true - Prefer var is used to declare variables with built-in system types such as int +## - false - Prefer explicit type over var to declare variables with built-in system types such as int +## // csharp_style_var_for_built_in_types = true +## var x = 5; +## +## // csharp_style_var_for_built_in_types = false +## int x = 5; +csharp_style_var_for_built_in_types = false -# IDE0010 -dotnet_diagnostic.IDE0010.severity = suggestion +## csharp_style_var_when_type_is_apparent +## - true - Prefer var when the type is already mentioned on the right-hand side of a declaration expression +## - false - Prefer explicit type when the type is already mentioned on the right-hand side of a declaration expression +## // csharp_style_var_when_type_is_apparent = true +## var obj = new Customer(); +## +## // csharp_style_var_when_type_is_apparent = false +## Customer obj = new Customer(); +csharp_style_var_when_type_is_apparent = true -# IDE0011 +## csharp_style_var_elsewhere +## - true - Prefer var over explicit type in all cases, unless overridden by another code style rule +## - false - Prefer explicit type over var in all cases, unless overridden by another code style rule +## // csharp_style_var_elsewhere = true +## var f = this.Init(); +## +## // csharp_style_var_elsewhere = false +## bool f = this.Init(); +csharp_style_var_elsewhere = false + +## Add missing cases to switch statement (IDE0010) +## This rule concerns specifying all the missing switch cases for a switch statement. A switch statement is considered incomplete in the following scenarios: +## An enum switch statement that's missing cases for one or more enum members. +## A switch statement with a missing default case. +## enum E +## { +## A, +## B +## } +## +## class C +## { +## // Code with violations +## int M(E e) +## { +## // IDE0010: Add missing cases +## switch (e) +## { +## case E.A: +## return 0; +## } +## +## return -1; +## } +## +## // Fixed code +## int M(E e) +## { +## switch (e) +## { +## case E.A: +## return 0; +## case E.B: +## return 1; +## default: +## return -1; +## } +## } +## } +dotnet_diagnostic.IDE0010.severity = warning + +## Add braces (IDE0011) +## This style rule concerns the use of curly braces { } to surround code blocks. dotnet_diagnostic.IDE0011.severity = warning -csharp_prefer_braces = when_multiline:warning -# IDE0016 -dotnet_diagnostic.IDE0016.severity = warning -csharp_style_throw_expression = true:warning +## Options: +## csharp_prefer_braces +## - true - Prefer curly braces even for one line of code +## - false - Prefer no curly braces if allowed +## - when_multiline - Prefer curly braces on multiple lines +## // csharp_prefer_braces = true +## if (test) { this.Display(); } +## +## // csharp_prefer_braces = false +## if (test) this.Display(); +## +## // csharp_prefer_braces = when_multiline +## if (test) this.Display(); +## else { this.Display(); Console.WriteLine("Multiline"); } +csharp_prefer_braces = when_multiline + +## Use throw expression (IDE0016) +## This style rule concerns the use of throw expressions instead of throw statements. Set the severity of rule IDE0016 to define how the rule should be enforced, for example, as a warning or an error. +dotnet_diagnostic.IDE0016.severity = none + +## Options: +## csharp_style_throw_expression +## - true - Prefer to use throw expressions instead of throw statements +## - false - Prefer to use throw statements instead of throw expressions +## // csharp_style_throw_expression = true +## this.s = s ?? throw new ArgumentNullException(nameof(s)); +## +## // csharp_style_throw_expression = false +## if (s == null) { throw new ArgumentNullException(nameof(s)); } +## this.s = s; +csharp_style_throw_expression = true -# IDE0017 +## Use object initializers (IDE0017) +## This style rule concerns the use of object initializers for object initialization. dotnet_diagnostic.IDE0017.severity = suggestion -dotnet_style_object_initializer = true:suggestion -# IDE0018 -dotnet_diagnostic.IDE0018.severity = suggestion -csharp_style_inlined_variable_declaration = true:suggestion +## Options: +## dotnet_style_object_initializer +## - true - Prefer objects to be initialized using object initializers when possible +## - false - Prefer objects to not be initialized using object initializers +## // dotnet_style_object_initializer = true +## var c = new Customer() { Age = 21 }; +## +## // dotnet_style_object_initializer = false +## var c = new Customer(); +## c.Age = 21; +dotnet_style_object_initializer = true -# IDE0019 +## Inline variable declaration (IDE0018) +## This style rule concerns whether out variables are declared inline or not. Starting in C# 7, you can declare an out variable in the argument list of a method call, rather than in a separate variable declaration. +dotnet_diagnostic.IDE0018.severity = warning + +## Options: +## csharp_style_inlined_variable_declaration +## - true - Prefer out variables to be declared inline in the argument list of a method call when possible +## - false - Prefer out variables to be declared before the method call +## // csharp_style_inlined_variable_declaration = true +## if (int.TryParse(value, out int i)) {...} +## +## // csharp_style_inlined_variable_declaration = false +## int i; +## if (int.TryParse(value, out i)) {...} +csharp_style_inlined_variable_declaration = true + +## Use pattern matching to avoid as followed by a null check (IDE0019) +## This style rule concerns the use of C# pattern matching over an as expression followed by a null check. This rule is similar to IDE0260, which flags the use of an as expression followed by a member read through the null-conditional operator. dotnet_diagnostic.IDE0019.severity = warning -csharp_style_pattern_matching_over_as_with_null_check = true:warning -# IDE0020 and IDE0038 +## Options: +## csharp_style_pattern_matching_over_as_with_null_check +## - true - Prefer pattern matching to determine if something is of a particular type +## - false - Prefer as expressions with null checks to determine if something is of a particular type +## // csharp_style_pattern_matching_over_as_with_null_check = true +## if (o is string s) {...} +## +## // csharp_style_pattern_matching_over_as_with_null_check = false +## var s = o as string; +## if (s != null) {...} +csharp_style_pattern_matching_over_as_with_null_check = true + +## Use pattern matching to avoid is check followed by a cast (with variable) (IDE0020) +## Use pattern matching to avoid is check followed by a cast (without variable) (IDE0038) +## This style rule concerns the use of C# pattern matching, for example, o is int i, over an is check followed by a cast, for example, if (o is int) { ... (int)o ... }. Enable either IDE0020 or IDE0038 based on whether or not the cast expression should be saved into a separate local variable: +## IDE0020: Cast expression is saved into a local variable. For example, if (o is int) { var i = (int)o; } saves the result of (int)o in a local variable. +## IDE0038: Cast expression is not saved into a local variable. For example, if (o is int) { if ((int)o == 1) { ... } } does not save the result of (int)o into a local variable. dotnet_diagnostic.IDE0020.severity = warning dotnet_diagnostic.IDE0038.severity = warning -csharp_style_pattern_matching_over_is_with_cast_check = true:warning -# IDE0021 +## Options: +## csharp_style_pattern_matching_over_is_with_cast_check +## - true - Prefer pattern matching instead of is expressions with type casts +## - false - Prefer is expressions with type casts instead of pattern matching +## // csharp_style_pattern_matching_over_is_with_cast_check = true +## if (o is int i) {...} +## +## // csharp_style_pattern_matching_over_is_with_cast_check = false +## if (o is int) {var i = (int)o; ... } +csharp_style_pattern_matching_over_is_with_cast_check = true + +## Use expression body for constructors (IDE0021) +## This style rule concerns the use of expression bodies versus block bodies for constructors. dotnet_diagnostic.IDE0021.severity = warning -csharp_style_expression_bodied_constructors = false:warning -# IDE0022 -dotnet_diagnostic.IDE0022.severity = suggestion -csharp_style_expression_bodied_methods = false:suggestion +## Options: +## csharp_style_expression_bodied_constructors +## - true - Prefer expression bodies for constructors +## - when_on_single_line - Prefer expression bodies for constructors when they will be a single line +## - false - Prefer block bodies for constructors +## // csharp_style_expression_bodied_constructors = true +## public Customer(int age) => Age = age; +## +## // csharp_style_expression_bodied_constructors = false +## public Customer(int age) { Age = age; } +csharp_style_expression_bodied_constructors = false + +## Use expression body for methods (IDE0022) +## This style rule concerns the use of expression bodies versus block bodies for methods. +dotnet_diagnostic.IDE0022.severity = warning + +## Options: +## csharp_style_expression_bodied_methods +## - true - Prefer expression bodies for methods +## - when_on_single_line - Prefer expression bodies for methods when they will be a single line +## - false - Prefer block bodies for methods +## // csharp_style_expression_bodied_methods = true +## public int GetAge() => this.Age; +## +## // csharp_style_expression_bodied_methods = false +## public int GetAge() { return this.Age; } +csharp_style_expression_bodied_methods = false + +## Use expression body for conversion operators (IDE0023) +## Use expression body for operators (IDE0024) +## This style rule concerns the use of expression bodies versus block bodies for operators. +dotnet_diagnostic.IDE0023.severity = warning +dotnet_diagnostic.IDE0024.severity = warning -# IDE0023 and IDE0024 -dotnet_diagnostic.IDE0023.severity = suggestion -dotnet_diagnostic.IDE0024.severity = suggestion -csharp_style_expression_bodied_operators = when_on_single_line:suggestion +## Options: +## csharp_style_expression_bodied_operators +## - true - Prefer expression bodies for operators +## - when_on_single_line - Prefer expression bodies for operators when they will be a single line +## - false - Prefer block bodies for operators +## // csharp_style_expression_bodied_operators = true +## public static ComplexNumber operator + (ComplexNumber c1, ComplexNumber c2) +## => new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); +## +## // csharp_style_expression_bodied_operators = false +## public static ComplexNumber operator + (ComplexNumber c1, ComplexNumber c2) +## { return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } +csharp_style_expression_bodied_operators = false -# IDE0025 +## Use expression body for properties (IDE0025) +## This style rule concerns the use of expression bodies versus block bodies for properties. dotnet_diagnostic.IDE0025.severity = warning -csharp_style_expression_bodied_properties = when_on_single_line:warning -# IDE0026 -dotnet_diagnostic.IDE0026.severity = suggestion -csharp_style_expression_bodied_indexers = when_on_single_line:suggestion +## Options: +## csharp_style_expression_bodied_properties +## - true - Prefer expression bodies for properties +## - when_on_single_line - Prefer expression bodies for properties when they will be a single line +## - false - Prefer block bodies for properties +## // csharp_style_expression_bodied_properties = true +## public int Age => _age; +## +## // csharp_style_expression_bodied_properties = false +## public int Age { get { return _age; }} +csharp_style_expression_bodied_properties = when_on_single_line + +## Use expression body for indexers (IDE0026) +## This style rule concerns the use of expression bodies versus block bodies for indexers. +dotnet_diagnostic.IDE0026.severity = warning + +## Options: +## csharp_style_expression_bodied_indexers +## - true - Prefer expression bodies for indexers +## - when_on_single_line - Prefer expression bodies for indexers when they will be a single line +## - false - Prefer block bodies for indexers +## // csharp_style_expression_bodied_indexers = true +## public T this[int i] => _values[i]; +## +## // csharp_style_expression_bodied_indexers = false +## public T this[int i] { get { return _values[i]; } } +csharp_style_expression_bodied_indexers = false + +## Use expression body for accessors (IDE0027) +## This style rule concerns the use of expression bodies versus block bodies for accessors. +dotnet_diagnostic.IDE0027.severity = warning -# IDE0027 -dotnet_diagnostic.IDE0027.severity = suggestion -csharp_style_expression_bodied_accessors = when_on_single_line:suggestion +## Options: +## csharp_style_expression_bodied_accessors +## - true - Prefer expression bodies for accessors +## - when_on_single_line - Prefer expression bodies for accessors when they will be a single line +## - false - Prefer block bodies for accessors +## // csharp_style_expression_bodied_accessors = true +## public int Age { get => _age; set => _age = value; } +## +## // csharp_style_expression_bodied_accessors = false +## public int Age { get { return _age; } set { _age = value; } } +csharp_style_expression_bodied_accessors = false -# IDE0028 +## Use collection initializers (IDE0028) +## This style rule concerns the use of collection initializers for collection initialization. dotnet_diagnostic.IDE0028.severity = suggestion -dotnet_style_collection_initializer = true:suggestion -# IDE0029 and IDE0030 +## Options: +## dotnet_style_collection_initializer +## - true - Prefer collections to be initialized using collection initializers when possible +## - false - Prefer collections to not be initialized using collection initializers +## // dotnet_style_collection_initializer = true +## var list = new List { 1, 2, 3 }; +## +## // dotnet_style_collection_initializer = false +## var list = new List(); +## list.Add(1); +## list.Add(2); +## list.Add(3); +dotnet_style_collection_initializer = true + +## Null check can be simplified (ternary conditional check) (IDE0029) +## Null check can be simplified (nullable ternary conditional check) (IDE0030) +## Null check can be simplified (if null check) (IDE0270) +## Rules IDE0029 and IDE0030 concern the use of null-coalescing expressions, for example, x ?? y, versus ternary conditional expressions with null checks, for example, x != null ? x : y. The rules differ with respect to the nullability of the expressions: +## IDE0029: Used when non-nullable expressions are involved. For example, this rule could recommend x ?? y instead of x != null ? x : y when x and y are non-nullable reference types. +## IDE0030: Used when nullable expressions are involved. For example, this rule could recommend x ?? y instead of x != null ? x : y when x and y are nullable value types or nullable reference types. +## Rule IDE0270 flags the use of a null check (== null or is null) instead of the null-coalescing operator (??). dotnet_diagnostic.IDE0029.severity = suggestion dotnet_diagnostic.IDE0030.severity = suggestion -dotnet_style_coalesce_expression = true:suggestion +dotnet_diagnostic.IDE0270.severity = suggestion + +## Options: +## dotnet_style_coalesce_expression +## - true - Prefer null-coalescing expressions. +## - false - Disables the rule. +dotnet_style_coalesce_expression = true -# IDE0031 +## Use null propagation (IDE0031) +## This style rule concerns the use of the null-conditional operator versus a ternary conditional expression with null check. dotnet_diagnostic.IDE0031.severity = suggestion -dotnet_style_null_propagation = true:suggestion -# IDE0032 -dotnet_diagnostic.IDE0032.severity = warning -dotnet_style_prefer_auto_properties = true:warning +## Options: +## dotnet_style_null_propagation +## - true - Prefer to use null-conditional operator when possible +## - false - Prefer to use ternary null checking where possible +## // dotnet_style_null_propagation = true +## var v = o?.ToString(); +## +## // dotnet_style_null_propagation = false +## var v = o == null ? null : o.ToString(); // or +## var v = o != null ? o.ToString() : null; +dotnet_style_null_propagation = true + +## Use auto-implemented property (IDE0032) +## This style rule concerns the use of auto-implemented properties versus properties with private backing fields. +dotnet_diagnostic.IDE0032.severity = suggestion + +## Options: +## dotnet_style_prefer_auto_properties +## - true - Prefer auto-implemented properties +## - false - Prefer properties with private backing fields +## // dotnet_style_prefer_auto_properties = true +## public int Age { get; } +## +## // dotnet_style_prefer_auto_properties = false +## private int age; +## +## public int Age +## { +## get +## { +## return age; +## } +## } +dotnet_style_prefer_auto_properties = true -# IDE0033 +## Use explicitly provided tuple name (IDE0033) +## This style rule concerns the use of explicit tuple names versus implicit 'ItemX' properties when accessing tuple fields. dotnet_diagnostic.IDE0033.severity = warning -dotnet_style_explicit_tuple_names = true:warning -# IDE0034 -dotnet_diagnostic.IDE0034.severity = warning -csharp_prefer_simple_default_expression = true:warning +## Options: +## dotnet_style_explicit_tuple_names +## - true - Prefer tuple names to ItemX properties +## - false - Prefer ItemX properties to tuple names +## // dotnet_style_explicit_tuple_names = true +## (string name, int age) customer = GetCustomer(); +## var name = customer.name; +## +## // dotnet_style_explicit_tuple_names = false +## (string name, int age) customer = GetCustomer(); +## var name = customer.Item1; +dotnet_style_explicit_tuple_names = true -# IDE0035 +## Simplify default expression (IDE0034) +## This style rule concerns using the default literal for default value expressions when the compiler can infer the type of the expression. +dotnet_diagnostic.IDE0034.severity = suggestion + +## Options: +## csharp_prefer_simple_default_expression +## - true - Prefer default over default(T) +## - false - Prefer default(T) over default +## // csharp_prefer_simple_default_expression = true +## void DoWork(CancellationToken cancellationToken = default) { ... } +## +## // csharp_prefer_simple_default_expression = false +## void DoWork(CancellationToken cancellationToken = default(CancellationToken)) { ... } +csharp_prefer_simple_default_expression = true + +## Remove unreachable code (IDE0035) +## This rule flags executable code within methods and properties that can never be reached, and hence can be removed. +## // Code with violations +## void M() +## { +## throw new System.Exception(); +## +## // IDE0035: Remove unreachable code +## int v = 0; +## } +## +## // Fixed code +## void M() +## { +## throw new System.Exception(); +## } dotnet_diagnostic.IDE0035.severity = warning -# IDE0036 +## Order modifiers (IDE0036) +## This rule lets you enforce a desired modifier sort order. +## When this rule is enabled and the associated options are set to a list of modifiers, prefer the specified ordering. +## When this rule is not enabled, no specific modifier order is preferred. dotnet_diagnostic.IDE0036.severity = warning + +## Options: +## csharp_preferred_modifier_order +## - One or more C# modifiers, such as public, private, and protected - +## // csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async +## class MyClass +## { +## private static readonly int _daysInYear = 365; +## } csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async -# IDE0037 -dotnet_diagnostic.IDE0037.severity = warning -dotnet_style_prefer_inferred_tuple_names = true:warning -dotnet_style_prefer_inferred_anonymous_type_member_names = true:warning +## Use inferred member name (IDE0037) +## This rule enforces whether inferred tuple element names and inferred anonymous type member names are preferred when the tuple or anonymous type is declared. +dotnet_diagnostic.IDE0037.severity = suggestion -# IDE0039 +## Options: +## dotnet_style_prefer_inferred_tuple_names +## - true - Prefer inferred tuple element names +## - false - Prefer explicit tuple element names +## // dotnet_style_prefer_inferred_tuple_names = true +## var tuple = (age, name); +## +## // dotnet_style_prefer_inferred_tuple_names = false +## var tuple = (age: age, name: name); +dotnet_style_prefer_inferred_tuple_names = false + +## dotnet_style_prefer_inferred_anonymous_type_member_names +## - true - Prefer inferred anonymous type member names +## - false - Prefer explicit anonymous type member names +## // dotnet_style_prefer_inferred_anonymous_type_member_names = true +## var anon = new { age, name }; +## +## // dotnet_style_prefer_inferred_anonymous_type_member_names = false +## var anon = new { age = age, name = name }; +dotnet_style_prefer_inferred_anonymous_type_member_names = true + +## Use local function instead of lambda (IDE0039) +## This style rule concerns the use of local functions versus lambda expressions (anonymous functions). dotnet_diagnostic.IDE0039.severity = suggestion -csharp_style_prefer_local_over_anonymous_function = true:suggestion -# IDE0040 +## Options: +## csharp_style_prefer_local_over_anonymous_function +## - true - Prefer local functions over anonymous functions +## - false - Prefer anonymous functions over local functions +## // csharp_style_prefer_local_over_anonymous_function = true +## int fibonacci(int n) +## { +## return n <= 1 ? 1 : fibonacci(n-1) + fibonacci(n-2); +## } +## +## // csharp_style_prefer_local_over_anonymous_function = false +## Func fibonacci = (int n) => +## { +## return n <= 1 ? 1 : fibonacci(n - 1) + fibonacci(n - 2); +## }; +csharp_style_prefer_local_over_anonymous_function = true + +## Add accessibility modifiers (IDE0040) +## This style rule concerns requiring accessibility modifiers in declarations. dotnet_diagnostic.IDE0040.severity = warning -dotnet_style_require_accessibility_modifiers = always:warning -# IDE0041 +## Options: +## dotnet_style_require_accessibility_modifiers +## - always - Prefer accessibility modifiers to be specified. +## - for_non_interface_members - Prefer accessibility modifiers except for public interface members. +## - never - Do not prefer accessibility modifiers to be specified. +## - omit_if_default - Prefer accessibility modifiers except if they are the default modifier. +## // dotnet_style_require_accessibility_modifiers = always +## // dotnet_style_require_accessibility_modifiers = for_non_interface_members +## class MyClass +## { +## private const string thisFieldIsConst = "constant"; +## } +## +## // dotnet_style_require_accessibility_modifiers = never +## class MyClass +## { +## const string thisFieldIsConst = "constant"; +## } +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +## Use 'is null' check (IDE0041) +## This style rule concerns the use of a null check with pattern matching versus the use of the equality operator (==) or calling xref:System.Object.ReferenceEquals(System.Object,System.Object)?displayProperty=nameWithType. dotnet_diagnostic.IDE0041.severity = warning -dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning -# IDE0042 -dotnet_diagnostic.IDE0042.severity = suggestion -csharp_style_deconstructed_variable_declaration = true:suggestion +## Options: +## dotnet_style_prefer_is_null_check_over_reference_equality_method +## - true - Prefer is null check +## - false - Prefer reference equality method +## // dotnet_style_prefer_is_null_check_over_reference_equality_method = true +## if (value is null) +## return; +## +## // dotnet_style_prefer_is_null_check_over_reference_equality_method = false +## if (object.ReferenceEquals(value, null)) +## return; +## +## // dotnet_style_prefer_is_null_check_over_reference_equality_method = false +## if ((object)o == null) +## return; +dotnet_style_prefer_is_null_check_over_reference_equality_method = true -# IDE0044 +## Deconstruct variable declaration (IDE0042) +## This style rule concerns the use of deconstruction in variable declarations, when possible. +dotnet_diagnostic.IDE0042.severity = silent + +## Options: +## csharp_style_deconstructed_variable_declaration +## - true - Prefer deconstructed variable declaration +## - false - Do not prefer deconstruction in variable declarations +## // csharp_style_deconstructed_variable_declaration = true +## var (name, age) = GetPersonTuple(); +## Console.WriteLine($"{name} {age}"); +## +## (int x, int y) = GetPointTuple(); +## Console.WriteLine($"{x} {y}"); +## +## // csharp_style_deconstructed_variable_declaration = false +## var person = GetPersonTuple(); +## Console.WriteLine($"{person.name} {person.age}"); +## +## (int x, int y) point = GetPointTuple(); +## Console.WriteLine($"{point.x} {point.y}"); +csharp_style_deconstructed_variable_declaration = true + +## Add readonly modifier (IDE0044) +## This style rule concerns specifying the readonly (C#) or ReadOnly (Visual Basic) modifier for private fields that are initialized (either inline or inside of a constructor) but never reassigned. dotnet_diagnostic.IDE0044.severity = warning -dotnet_style_readonly_field = true:warning -# IDE0045 +## Options: +## dotnet_style_readonly_field +## - true - Prefer that private fields be marked readonly if they're only ever assigned inline or in a constructor +## - false - Specify no preference over whether private fields are marked readonly +## // dotnet_style_readonly_field = true +## class MyClass +## { +## private readonly int _daysInYear = 365; +## } +dotnet_style_readonly_field = true + +## Use conditional expression for assignment (IDE0045) +## This style rule concerns the use of a ternary conditional expression versus an if-else statement for assignments that require conditional logic. dotnet_diagnostic.IDE0045.severity = suggestion -dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion -# IDE0046 +## Options: +## dotnet_style_prefer_conditional_expression_over_assignment +## - true - Prefer assignments with a ternary conditional +## - false - Prefer assignments with an if-else statement +## // dotnet_style_prefer_conditional_expression_over_assignment = true +## string s = expr ? "hello" : "world"; +## +## // dotnet_style_prefer_conditional_expression_over_assignment = false +## string s; +## if (expr) +## { +## s = "hello"; +## } +## else +## { +## s = "world"; +## } +dotnet_style_prefer_conditional_expression_over_assignment = true + +## Use conditional expression for return (IDE0046) +## This style rule concerns the use of a ternary conditional expression versus an if-else statement for return statements that require conditional logic. dotnet_diagnostic.IDE0046.severity = suggestion -dotnet_style_prefer_conditional_expression_over_return = true:suggestion -# IDE0047 and IDE0048 -dotnet_diagnostic.IDE0047.severity = warning +## Options: +## dotnet_style_prefer_conditional_expression_over_return +## - true - Prefer return statements to use a ternary conditional +## - false - Prefer return statements to use an if-else statement +## // dotnet_style_prefer_conditional_expression_over_return = true +## return expr ? "hello" : "world" +## +## // dotnet_style_prefer_conditional_expression_over_return = false +## if (expr) +## { +## return "hello"; +## } +## else +## { +## return "world"; +## } +dotnet_style_prefer_conditional_expression_over_return = true + +## Remove unnecessary parentheses (IDE0047) +## Add parentheses for clarity (IDE0048) +## The style rules in this section concern parentheses preferences, including the use of parentheses to clarify precedence for arithmetic, relational, and other binary operators. +dotnet_diagnostic.IDE0047.severity = suggestion dotnet_diagnostic.IDE0048.severity = warning -dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning -dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning -dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning -dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning -# IDE0049 +## Options: +## dotnet_style_parentheses_in_arithmetic_binary_operators +## - always_for_clarity - Prefer parentheses to clarify arithmetic operator precedence +## - never_if_unnecessary - Prefer no parentheses when arithmetic operator precedence is obvious +## // dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity +## var v = a + (b * c); +## +## // dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary +## var v = a + b * c; +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity + +## dotnet_style_parentheses_in_relational_binary_operators +## - always_for_clarity - Prefer parentheses to clarify relational operator precedence +## - never_if_unnecessary - Prefer to not have parentheses when relational operator precedence is obvious +## // dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity +## var v = (a < b) == (c > d); +## +## // dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary +## var v = a < b == c > d; +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary + +## dotnet_style_parentheses_in_other_binary_operators +## - always_for_clarity - Prefer parentheses to clarify other binary operator precedence +## - never_if_unnecessary - Prefer to not have parentheses when other binary operator precedence is obvious +## // dotnet_style_parentheses_in_other_binary_operators = always_for_clarity +## var v = a || (b && c); +## +## // dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary +## var v = a || b && c; +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary + +## dotnet_style_parentheses_in_other_operators +## - always_for_clarity - Prefer parentheses to clarify other operator precedence +## - never_if_unnecessary - Prefer to not have parentheses when other operator precedence is obvious +## // dotnet_style_parentheses_in_other_operators = always_for_clarity +## var v = (a.b).Length; +## +## // dotnet_style_parentheses_in_other_operators = never_if_unnecessary +## var v = a.b.Length; +dotnet_style_parentheses_in_other_operators = never_if_unnecessary + +## Use language keywords instead of framework type names for type references (IDE0049) +## This rule concerns the use of language keywords, where they exist, instead of framework type names. dotnet_diagnostic.IDE0049.severity = warning -dotnet_style_predefined_type_for_locals_parameters_members = true:warning -dotnet_style_predefined_type_for_member_access = true:warning -# IDE0050-52 +## Options: +## dotnet_style_predefined_type_for_locals_parameters_members +## - true - Prefer the language keyword for local variables, method parameters, and class members +## - false - Prefer the type name for local variables, method parameters, and class members +## // dotnet_style_predefined_type_for_locals_parameters_members = true +## private int _member; +## +## // dotnet_style_predefined_type_for_locals_parameters_members = false +## private Int32 _member; +dotnet_style_predefined_type_for_locals_parameters_members = true + +## dotnet_style_predefined_type_for_member_access +## - true - Prefer the language keyword for member access expressions +## - false - Prefer the type name for member access expressions +## // dotnet_style_predefined_type_for_member_access = true +## var local = int.MaxValue; +## +## // dotnet_style_predefined_type_for_member_access = false +## var local = Int32.MaxValue; +dotnet_style_predefined_type_for_member_access = true + +## Convert anonymous type to tuple (IDE0050) +## This rule recommends use of tuples over anonymous types, when the anonymous type has two or more fields. +## // Code with violations +## var t1 = new { a = 1, b = 2 }; +## +## // Fixed code +## var t1 = (a: 1, b: 2); dotnet_diagnostic.IDE0050.severity = warning + +## Remove unused private member (IDE0051) +## This rule flags unused private methods, fields, properties, and events that have no read or write references. +## // Code with violations +## class C +## { +## // IDE0051: Remove unused private members +## private readonly int _fieldPrivate; +## private int PropertyPrivate => 1; +## private int GetNumPrivate() => 1; +## +## // No IDE0051 +## internal readonly int FieldInternal; +## private readonly int _fieldPrivateUsed; +## public int PropertyPublic => _fieldPrivateUsed; +## private int GetNumPrivateUsed() => 1; +## internal int GetNumInternal() => GetNumPrivateUsed(); +## public int GetNumPublic() => GetNumPrivateUsed(); +## } +## +## // Fixed code +## class C +## { +## // No IDE0051 +## internal readonly int FieldInternal; +## private readonly int _fieldPrivateUsed; +## public int PropertyPublic => _fieldPrivateUsed; +## private int GetNumPrivateUsed() => 1; +## internal int GetNumInternal() => GetNumPrivateUsed(); +## public int GetNumPublic() => GetNumPrivateUsed(); +## } dotnet_diagnostic.IDE0051.severity = warning + +## Remove unread private member (IDE0052) +## This rule flags private fields and properties that have one or more write references but no read references. In this scenario, some parts of the code can be refactored or removed to fix maintainability, performance, or functional issues. +## // Code with violations +## class C +## { +## // IDE0052: Remove unread private members +## private readonly int _field1; +## private int _field2; +## private int Property { get; set; } +## +## public C() +## { +## _field1 = 0; +## } +## +## public void SetMethod() +## { +## _field2 = 0; +## Property = 0; +## } +## } +## +## // Fixed code +## class C +## { +## public C() +## { +## } +## +## public void SetMethod() +## { +## } +## } dotnet_diagnostic.IDE0052.severity = warning -# IDE0053 +## Use expression body for lambdas (IDE0053) +## This style rule concerns the use of expression bodies versus block bodies for lambda expressions. dotnet_diagnostic.IDE0053.severity = suggestion -csharp_style_expression_bodied_lambdas = :suggestion -# IDE0054 and IDE0074 -dotnet_diagnostic.IDE0054.severity = suggestion -dotnet_diagnostic.IDE0074.severity = suggestion -dotnet_style_prefer_compound_assignment = true:suggestion +## Options: +## csharp_style_expression_bodied_lambdas +## - true - Prefer expression bodies for lambdas +## - when_on_single_line - Prefer expression bodies for lambdas when they'll be a single line +## - false - Prefer block bodies for lambdas +## // csharp_style_expression_bodied_lambdas = true +## Func square = x => x * x; +## +## // csharp_style_expression_bodied_lambdas = false +## Func square = x => { return x * x; }; +csharp_style_expression_bodied_lambdas = when_on_single_line + +## Use compound assignment (IDE0054) +## Use coalesce compound assignment (IDE0074) +## These rules concern the use of compound assignment. IDE0074 is reported for coalesce compound assignments and IDE0054 is reported for other compound assignments. +dotnet_diagnostic.IDE0054.severity = warning +dotnet_diagnostic.IDE0074.severity = none + +## Options: +## dotnet_style_prefer_compound_assignment +## - true - Prefer compound assignment expressions +## - false - Don't prefer compound assignment expressions +## // dotnet_style_prefer_compound_assignment = true +## x += 5; +## +## // dotnet_style_prefer_compound_assignment = false +## x = x + 5; +dotnet_style_prefer_compound_assignment = true + +## Formatting rule (IDE0055) +## +dotnet_diagnostic.IDE0055.severity = None -# IDE0055 -dotnet_diagnostic.IDE0055.severity = warning +## Options: +## dotnet_sort_system_directives_first +## - true - Sort System.* using directives alphabetically, and place them before other using directives. +## - false - Do not place System.* using directives before other using directives. +## // dotnet_sort_system_directives_first = true +## using System.Collections.Generic; +## using System.Threading.Tasks; +## using Octokit; +## +## // dotnet_sort_system_directives_first = false +## using System.Collections.Generic; +## using Octokit; +## using System.Threading.Tasks; dotnet_sort_system_directives_first = false + +## dotnet_separate_import_directive_groups +## - true - Place a blank line between using directive groups. +## - false - Do not place a blank line between using directive groups. +## // dotnet_separate_import_directive_groups = true +## using System.Collections.Generic; +## using System.Threading.Tasks; +## +## using Octokit; +## +## // dotnet_separate_import_directive_groups = false +## using System.Collections.Generic; +## using System.Threading.Tasks; +## using Octokit; dotnet_separate_import_directive_groups = false + +## csharp_new_line_before_open_brace +## - all - Require braces to be on a new line for all expressions ("Allman" style). +## - none - Require braces to be on the same line for all expressions ("K&R"). +## - accessors, anonymous_methods, anonymous_types, control_blocks, events, indexers,lambdas, local_functions, methods, object_collection_array_initializers, properties, types - Require braces to be on a new line for the specified code element ("Allman" style). +## // csharp_new_line_before_open_brace = all +## void MyMethod() +## { +## if (...) +## { +## ... +## } +## } +## +## // csharp_new_line_before_open_brace = none +## void MyMethod() { +## if (...) { +## ... +## } +## } csharp_new_line_before_open_brace = all + +## csharp_new_line_before_else +## - true - Place else statements on a new line. +## - false - Place else statements on the same line. +## // csharp_new_line_before_else = true +## if (...) { +## ... +## } +## else { +## ... +## } +## +## // csharp_new_line_before_else = false +## if (...) { +## ... +## } else { +## ... +## } csharp_new_line_before_else = true + +## csharp_new_line_before_catch +## - true - Place catch statements on a new line. +## - false - Place catch statements on the same line. +## // csharp_new_line_before_catch = true +## try { +## ... +## } +## catch (Exception e) { +## ... +## } +## +## // csharp_new_line_before_catch = false +## try { +## ... +## } catch (Exception e) { +## ... +## } csharp_new_line_before_catch = true + +## csharp_new_line_before_finally +## - true - Require finally statements to be on a new line after the closing brace. +## - false - Require finally statements to be on the same line as the closing brace. +## // csharp_new_line_before_finally = true +## try { +## ... +## } +## catch (Exception e) { +## ... +## } +## finally { +## ... +## } +## +## // csharp_new_line_before_finally = false +## try { +## ... +## } catch (Exception e) { +## ... +## } finally { +## ... +## } csharp_new_line_before_finally = true + +## csharp_new_line_before_members_in_object_initializers +## - true - Require members of object initializers to be on separate lines +## - false - Require members of object initializers to be on the same line +## // csharp_new_line_before_members_in_object_initializers = true +## var z = new B() +## { +## A = 3, +## B = 4 +## } +## +## // csharp_new_line_before_members_in_object_initializers = false +## var z = new B() +## { +## A = 3, B = 4 +## } csharp_new_line_before_members_in_object_initializers = true + +## csharp_new_line_before_members_in_anonymous_types +## - true - Require members of anonymous types to be on separate lines +## - false - Require members of anonymous types to be on the same line +## // csharp_new_line_before_members_in_anonymous_types = true +## var z = new +## { +## A = 3, +## B = 4 +## } +## +## // csharp_new_line_before_members_in_anonymous_types = false +## var z = new +## { +## A = 3, B = 4 +## } csharp_new_line_before_members_in_anonymous_types = true + +## csharp_new_line_between_query_expression_clauses +## - true - Require elements of query expression clauses to be on separate lines +## - false - Require elements of query expression clauses to be on the same line +## // csharp_new_line_between_query_expression_clauses = true +## var q = from a in e +## from b in e +## select a * b; +## +## // csharp_new_line_between_query_expression_clauses = false +## var q = from a in e from b in e +## select a * b; csharp_new_line_between_query_expression_clauses = true + +## csharp_indent_case_contents +## - true - Indent switch case contents +## - false - Do not indent switch case contents +## // csharp_indent_case_contents = true +## switch(c) { +## case Color.Red: +## Console.WriteLine("The color is red"); +## break; +## case Color.Blue: +## Console.WriteLine("The color is blue"); +## break; +## default: +## Console.WriteLine("The color is unknown."); +## break; +## } +## +## // csharp_indent_case_contents = false +## switch(c) { +## case Color.Red: +## Console.WriteLine("The color is red"); +## break; +## case Color.Blue: +## Console.WriteLine("The color is blue"); +## break; +## default: +## Console.WriteLine("The color is unknown."); +## break; +## } csharp_indent_case_contents = true + +## csharp_indent_switch_labels +## - true - Indent switch labels +## - false - Do not indent switch labels +## // csharp_indent_switch_labels = true +## switch(c) { +## case Color.Red: +## Console.WriteLine("The color is red"); +## break; +## case Color.Blue: +## Console.WriteLine("The color is blue"); +## break; +## default: +## Console.WriteLine("The color is unknown."); +## break; +## } +## +## // csharp_indent_switch_labels = false +## switch(c) { +## case Color.Red: +## Console.WriteLine("The color is red"); +## break; +## case Color.Blue: +## Console.WriteLine("The color is blue"); +## break; +## default: +## Console.WriteLine("The color is unknown."); +## break; +## } csharp_indent_switch_labels = true -csharp_indent_labels = no_cahnge + +## csharp_indent_labels +## - flush_left - Labels are placed at the leftmost column +## - one_less_than_current - Labels are placed at one less indent to the current context +## - no_change - Labels are placed at the same indent as the current context +## // csharp_indent_labels= flush_left +## class C +## { +## private string MyMethod(...) +## { +## if (...) { +## goto error; +## } +## error: +## throw new Exception(...); +## } +## } +## +## // csharp_indent_labels = one_less_than_current +## class C +## { +## private string MyMethod(...) +## { +## if (...) { +## goto error; +## } +## error: +## throw new Exception(...); +## } +## } +## +## // csharp_indent_labels= no_change +## class C +## { +## private string MyMethod(...) +## { +## if (...) { +## goto error; +## } +## error: +## throw new Exception(...); +## } +## } +# csharp_indent_labels = + +## csharp_indent_block_contents +## - true - Indent block contents. +## - false - Don't indent block contents. +## // csharp_indent_block_contents = true +## static void Hello() +## { +## Console.WriteLine("Hello"); +## } +## +## // csharp_indent_block_contents = false +## static void Hello() +## { +## Console.WriteLine("Hello"); +## } csharp_indent_block_contents = true + +## csharp_indent_braces +## - true - Indent curly braces. +## - false - Don't indent curly braces. +## // csharp_indent_braces = true +## static void Hello() +## { +## Console.WriteLine("Hello"); +## } +## +## // csharp_indent_braces = false +## static void Hello() +## { +## Console.WriteLine("Hello"); +## } csharp_indent_braces = false + +## csharp_indent_case_contents_when_block +## - true - When it's a block, indent the statement list and curly braces for a case in a switch statement. +## - false - When it's a block, don't indent the statement list and curly braces for a case in a switch statement. +## // csharp_indent_case_contents_when_block = true +## case 0: +## { +## Console.WriteLine("Hello"); +## break; +## } +## +## // csharp_indent_case_contents_when_block = false +## case 0: +## { +## Console.WriteLine("Hello"); +## break; +## } csharp_indent_case_contents_when_block = false -csharp_space_after_cast = false + +## csharp_space_after_cast +## - true - Place a space character between a cast and the value +## - false - Remove space between the cast and the value +## // csharp_space_after_cast = true +## int y = (int) x; +## +## // csharp_space_after_cast = false +## int y = (int)x; +csharp_space_after_cast = true + +## csharp_space_after_keywords_in_control_flow_statements +## - true - Place a space character after a keyword in a control flow statement such as a for loop +## - false - Remove space after a keyword in a control flow statement such as a for loop +## // csharp_space_after_keywords_in_control_flow_statements = true +## for (int i;i wordCount, string searchWord) +## { +## _ = wordCount.TryGetValue(searchWord, out var count); +## return count; +## } +## +## // csharp_style_unused_value_assignment_preference = unused_local_variable +## int GetCount(Dictionary wordCount, string searchWord) +## { +## var unused = wordCount.TryGetValue(searchWord, out var count); +## return count; +## } +csharp_style_unused_value_assignment_preference = discard_variable -# IDE0062 -dotnet_diagnostic.IDE0062.severity = suggestion -csharp_prefer_static_local_function = true:suggestion +## Remove unused parameter (IDE0060) +## This rule flags unused parameters. +## This rule does not flag parameters that are named with the discard symbol _. In addition, the rule ignores parameters that are named with the discard symbol followed by an integer, for example, _1. This behavior reduces warning noise on parameters that are needed for signature requirements, for example, a method used as a delegate, a parameter with special attributes, or a parameter whose value is implicitly accessed at run time by a framework but is not referenced in code. +dotnet_diagnostic.IDE0060.severity = warning -# IDE0063 -dotnet_diagnostic.IDE0063.severity = warning -csharp_prefer_simple_using_statement = true:warning +## Options: +## dotnet_code_quality_unused_parameters +## - all - Flag methods with any accessibility that contain unused parameters +## - non_public - Flag only non-public methods that contain unused parameters +## // dotnet_code_quality_unused_parameters = all +## public int GetNum1(int unusedParam) { return 1; } +## internal int GetNum2(int unusedParam) { return 1; } +## private int GetNum3(int unusedParam) { return 1; } +## +## // dotnet_code_quality_unused_parameters = non_public +## internal int GetNum4(int unusedParam) { return 1; } +## private int GetNum5(int unusedParam) { return 1; } +dotnet_code_quality_unused_parameters = all -# IDE0064 -dotnet_diagnostic.IDE0064.severity = warning +## Use expression body for local functions (IDE0061) +## This style rule concerns the use of expression bodies versus block bodies for local functions. Local functions are private methods of a type that are nested in another member. +dotnet_diagnostic.IDE0061.severity = warning -# IDE0065 +## Options: +## csharp_style_expression_bodied_local_functions +## - true - Prefer expression bodies for local functions +## - when_on_single_line - Prefer expression bodies for local functions when they'll be a single line +## - false - Prefer block bodies for local functions +## // csharp_style_expression_bodied_local_functions = true +## void M() +## { +## Hello(); +## void Hello() => Console.WriteLine("Hello"); +## } +## +## // csharp_style_expression_bodied_local_functions = false +## void M() +## { +## Hello(); +## void Hello() +## { +## Console.WriteLine("Hello"); +## } +## } +csharp_style_expression_bodied_local_functions = false + +## Make local function static (IDE0062) +## This style rule concerns the preference of marking local functions as static or not. +dotnet_diagnostic.IDE0062.severity = warning + +## Options: +## csharp_prefer_static_local_function +## - true - Prefer local functions to be marked static +## - false - Prefer local functions not to be marked static +## // csharp_prefer_static_local_function = true +## void M() +## { +## Hello(); +## static void Hello() +## { +## Console.WriteLine("Hello"); +## } +## } +## +## // csharp_prefer_static_local_function = false +## void M() +## { +## Hello(); +## void Hello() +## { +## Console.WriteLine("Hello"); +## } +## } +csharp_prefer_static_local_function = true + +## Use simple using statement (IDE0063) +## This style rule concerns the use of using statements without curly braces, also known as using declarations. This alternative syntax was introduced in C# 8.0. +dotnet_diagnostic.IDE0063.severity = suggestion + +## Options: +## csharp_prefer_simple_using_statement +## - true - Prefer to use a using declaration +## - false - Prefer to use a using statement with curly braces +## // csharp_prefer_simple_using_statement = true +## using var a = b; +## +## // csharp_prefer_simple_using_statement = false +## using (var a = b) { } +csharp_prefer_simple_using_statement = true + +## Make struct fields writable (IDE0064) +## This rule detects structs that contain one or more readonly fields and also contain an assignment to this outside of the constructor. The rule recommends converting readonly fields to non-read only, that is, writable. Marking such struct fields as readonly can lead to unexpected behavior, because the value assigned to the field can change when this is assigned outside the constructor. +## // Code with violations +## struct MyStruct +## { +## public readonly int Value; +## +## public MyStruct(int value) +## { +## Value = value; +## } +## +## public void Test() +## { +## this = new MyStruct(5); +## } +## } +## +## // Fixed code +## struct MyStruct +## { +## public int Value; +## +## public MyStruct(int value) +## { +## Value = value; +## } +## +## public void Test() +## { +## this = new MyStruct(5); +## } +## } +dotnet_diagnostic.IDE0064.severity = none + +## using directive placement (IDE0065) +## This style rule concerns the preference of placing using directives outside or inside the namespace. dotnet_diagnostic.IDE0065.severity = warning -csharp_using_directive_placement = outside_namespace:warning -# IDE0066 -dotnet_diagnostic.IDE0066.severity = warning -csharp_style_prefer_switch_expression = true:warning +## Options: +## csharp_using_directive_placement +## - outside_namespace - Prefer using directives to be placed outside the namespace +## - inside_namespace - Prefer using directives to be placed inside the namespace +## // csharp_using_directive_placement = outside_namespace +## using System; +## +## namespace Conventions +## { +## ... +## } +## +## // csharp_using_directive_placement = inside_namespace +## namespace Conventions +## { +## using System; +## ... +## } +csharp_using_directive_placement = outside_namespace + +## Use switch expression (IDE0066) +## This style rule concerns the use of switch expressions, which were introduced in C# 8.0, versus switch statements. +dotnet_diagnostic.IDE0066.severity = suggestion -# IDE0070 +## Options: +## csharp_style_prefer_switch_expression +## - true - Prefer to use a switch expression +## - false - Prefer to use a switch statement +## // csharp_style_prefer_switch_expression = true +## return x switch +## { +## 1 => 1 * 1, +## 2 => 2 * 2, +## _ => 0, +## }; +## +## // csharp_style_prefer_switch_expression = false +## switch (x) +## { +## case 1: +## return 1 * 1; +## case 2: +## return 2 * 2; +## default: +## return 0; +## } +csharp_style_prefer_switch_expression = true + +## Use System.HashCode.Combine (IDE0070) +## This rule recommends the use of the xref:System.HashCode.Combine%2A?displayProperty=fullName method to compute a hash code instead of using custom hash code computation logic. +## class B +## { +## public override int GetHashCode() => 0; +## } +## +## class C : B +## { +## int j; +## +## // Code with violations +## public override int GetHashCode() +## { +## // IDE0070: GetHashCode can be simplified. +## var hashCode = 339610899; +## hashCode = hashCode * -1521134295 + base.GetHashCode(); +## hashCode = hashCode * -1521134295 + j.GetHashCode(); +## return hashCode; +## } +## +## // Fixed code +## public override int GetHashCode() +## { +## return System.HashCode.Combine(base.GetHashCode(), j); +## } +## } dotnet_diagnostic.IDE0070.severity = warning -# IDE0071 -dotnet_diagnostic.IDE0071.severity = none -dotnet_style_prefer_simplified_interpolation = true:suggestion +## Simplify interpolation (IDE0071) +## This style rule concerns with simplification of interpolated strings to improve code readability. It recommends removal of certain explicit method calls, such as ToString(), when the same method would be implicitly invoked by the compiler if the explicit method call is removed. +dotnet_diagnostic.IDE0071.severity = suggestion + +## Options: +## dotnet_style_prefer_simplified_interpolation +## - true - Prefer simplified interpolated strings +## - false - Do not prefer simplified interpolated strings +## // dotnet_style_prefer_simplified_interpolation = true +## var str = $"prefix {someValue} suffix"; +## +## // dotnet_style_prefer_simplified_interpolation = false +## var str = $"prefix {someValue.ToString()} suffix"; +dotnet_style_prefer_simplified_interpolation = true + +## Add missing cases to switch expression (IDE0072) +## This rule concerns specifying all the missing cases for a switch expression. A switch expression is considered incomplete with missing cases in following scenarios: +## When an enum switch expression is missing cases for one or more enum members. +## When the fall-through case _ is missing. +## enum E +## { +## A, +## B +## } +## +## class C +## { +## // Code with violations +## int M(E e) +## { +## // IDE0072: Add missing cases +## return e switch +## { +## E.A => 0, +## _ => -1, +## }; +## } +## +## // Fixed code +## int M(E e) +## { +## return e switch +## { +## E.A => 0, +## E.B => 1, +## _ => -1, +## }; +## } +## } +dotnet_diagnostic.IDE0072.severity = suggestion + +## Require file header (IDE0073) +## This style rule concerns providing a file header at top of source code files. +dotnet_diagnostic.IDE0073.severity = none + +## Options: +## file_header_template +## - non-empty string, optionally containing a {fileName} placeholder - Prefer the string as the required file header. +## - unset or empty string - Do not require a file header. +## // file_header_template = Copyright (c) SomeCorp. All rights reserved.\nLicensed under the xyz license. +## +## // Copyright (c) SomeCorp. All rights reserved. +## // Licensed under the xyz license. +## namespace N1 +## { +## class C1 { } +## } +## +## // file_header_template = unset +## // OR +## // file_header_template = +## namespace N2 +## { +## class C2 { } +## } +# file_header_template = + +## Simplify conditional expression (IDE0075) +## This style rule concerns simplifying conditional expressions that return a constant value of true or false versus retaining conditional expressions with explicit true or false return values. +dotnet_diagnostic.IDE0075.severity = warning -# IDE0072 -dotnet_diagnostic.IDE0072.severity = warning +## Options: +## dotnet_style_prefer_simplified_boolean_expressions +## - true - Prefer simplified conditional expressions +## - false - Do not prefer simplified conditional expressions +## // dotnet_style_prefer_simplified_boolean_expressions = true +## var result1 = M1() && M2(); +## var result2 = M1() || M2(); +## +## // dotnet_style_prefer_simplified_boolean_expressions = false +## var result1 = M1() && M2() ? true : false; +## var result2 = M1() ? true : M2(); +dotnet_style_prefer_simplified_boolean_expressions = true -# IDE0073 -file_header_template = unset +## Remove invalid global SuppressMessageAttribute (IDE0076) +## This rule flags global SuppressMessageAttributes that have an invalid Scope or Target. The attribute should either be removed or fixed to refer to a valid scope and target symbol. +## // IDE0076: Invalid target '~F:N.C.F2' - no matching field named 'F2' +## [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "member", Target = "~F:N.C.F2")] +## // IDE0076: Invalid scope 'property' +## [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "property", Target = "~P:N.C.P")] +## +## // Fixed code +## [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "member", Target = "~F:N.C.F")] +## [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "member", Target = "~P:N.C.P")] +## +## namespace N +## { +## class C +## { +## public int F; +## public int P { get; } +## } +## } +dotnet_diagnostic.IDE0076.severity = none -# IDE0075 -dotnet_diagnostic.IDE0075.severity = suggestion -dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +## Avoid legacy format target in global SuppressMessageAttribute (IDE0077) +## This rule flags global SuppressMessageAttributes that specify Target using the legacy FxCop target string format. Using the legacy format Target is known to have performance problems and should be avoided. For more information, see dotnet/roslyn issue 44362. +## The recommended format for Target is the documentation ID format. For information about documentation IDs, see Documentation ID format. +## [!TIP] +## Visual Studio 2019 provides a code fix to automatically change the Target of the attribute to the recommended format. +## // IDE0077: Legacy format target 'N.C.#F' +## [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "member", Target = "N.C.#F")] +## +## // Fixed code +## [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "Id: Title", Scope = "member", Target = "~F:N.C.F")] +## +## namespace N +## { +## class C +## { +## public int F; +## } +## } +dotnet_diagnostic.IDE0077.severity = none -# IDE0078 -# dotnet_diagnostic.IDE0078.severity = warning -# csharp_style_prefer_pattern_matching = true:suggestion -csharp_style_prefer_pattern_matching = true:none -csharp_style_pattern_matching_over_as_with_null_check = true:warning +## Use pattern matching (IDE0078) +## Use pattern matching (IDE0260) +## This style rule concerns the use of C# pattern matching constructs. +## IDE0260 specifically flags the use of an as expression followed by a member read through the null-conditional operator. This rule is similar to IDE0019, which flags the use of an as expression followed by a null check. +dotnet_diagnostic.IDE0078.severity = warning +dotnet_diagnostic.IDE0260.severity = suggestion -# IDE0082 -dotnet_diagnostic.IDE0082.severity = warning +## Options: +## csharp_style_prefer_pattern_matching +## - true - Prefer to use pattern matching constructs, when possible +## - false - Prefer not to use pattern matching constructs. +csharp_style_prefer_pattern_matching = true -# IDE0083 +## Options: +## csharp_style_pattern_matching_over_as_with_null_check +## - true - Prefer pattern matching to determine if something is of a particular type +## - false - Prefer as expressions with null checks to determine if something is of a particular type +## // csharp_style_pattern_matching_over_as_with_null_check = true +## if (o is string s) {...} +## +## // csharp_style_pattern_matching_over_as_with_null_check = false +## var s = o as string; +## if (s != null) {...} +csharp_style_pattern_matching_over_as_with_null_check = true + +## Remove unnecessary suppression (IDE0079) +## This rule flags unnecessary pragma and xref:System.Diagnostics.CodeAnalysis.SuppressMessageAttribute attribute suppressions in source. +## Source suppressions suppress violations of compiler and analyzer rules in specific places but not in other parts of the source code. You generally use them to suppress false positives or less important violations that you don't intend to fix. However, suppressions often become stale. This can happen if a rule is fixed to prevent false positives or you refactor your code and, in doing so, render the suppressions redundant. This rule helps to identify redundant suppressions, which can be removed. +## [!NOTE] +## Rule IDE0079 only flags violations in files that are open in the Visual Studio editor. It's not available for command-line builds. +## using System.Diagnostics.CodeAnalysis; +## +## class C1 +## { +## // Necessary pragma suppression +## #pragma warning disable IDE0051 // IDE0051: Remove unused member +## private int UnusedMethod() => 0; +## #pragma warning restore IDE0051 +## +## // IDE0079: Unnecessary pragma suppression +## #pragma warning disable IDE0051 // IDE0051: Remove unused member +## private int UsedMethod() => 0; +## #pragma warning restore IDE0051 +## +## public int PublicMethod() => UsedMethod(); +## } +## +## class C2 +## { +## // Necessary SuppressMessage attribute suppression +## [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "")] +## private int _unusedField; +## +## // IDE0079: Unnecessary SuppressMessage attribute suppression +## [SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "")] +## private int _usedField; +## +## public int PublicMethod2() => _usedField; +## } +dotnet_diagnostic.IDE0079.severity = suggestion + +## Options: +## dotnet_remove_unnecessary_suppression_exclusions +## - , separated list of rule IDs or categories (prefixed with category:) - Excludes suppressions for the listed rules +## - all - Disables the rule (all rule IDs excluded) +## - none - Enables the rule for all rules (no exclusions) +## using System.Diagnostics.CodeAnalysis; +## +## class C1 +## { +## // 'dotnet_remove_unnecessary_suppression_exclusions = IDE0051' +## +## // Unnecessary pragma suppression, but not flagged by IDE0079 +## #pragma warning disable IDE0051 // IDE0051: Remove unused member +## private int UsedMethod() => 0; +## #pragma warning restore IDE0051 +## +## public int PublicMethod() => UsedMethod(); +## } +dotnet_remove_unnecessary_suppression_exclusions = none + +## Remove unnecessary suppression operator (IDE0080) +## This rule flags an unnecessary suppression or null-forgiving operator. The operator is unnecessary when it's used in a context where it has no effect. Use of the suppression operator, for example, x!, declares that the expression x of a reference type isn't null. However, when used in a context of another operator, for example, the is operator in o !is string, it has no effect and can be removed. +## // Code with violations +## if (o !is string) { } +## +## // Potential fixes: +## // 1. +## if (o is not string) { } +## +## // 2. +## if (!(o is string)) { } +## +## // 3. +## if (o is string) { } +dotnet_diagnostic.IDE0080.severity = warning + +## Remove ByVal (IDE0081) +## This rule flags an unnecessary ByVal keyword in a parameter declaration in Visual Basic. Parameters in Visual Basic are ByVal by default, hence you do not need to explicitly specify it in method signatures. It tends to produce noisy code and often leads to the non-default ByRef keyword being overlooked. +dotnet_diagnostic.IDE0081.severity = none + +## Convert typeof to nameof (IDE0082) +## This style rule recommends use of the nameof operator over the typeof operator followed by xref:System.Reflection.MemberInfo.Name member access. It only fires when the name will be identical in both cases. +## // Code with violations +## var n1 = typeof(T).Name; +## var n2 = typeof(int).Name; +## +## // Fixed code +## var n1 = nameof(T); +## var n2 = nameof(Int32); +dotnet_diagnostic.IDE0082.severity = suggestion + +## Use pattern matching (not operator) (IDE0083) +## This style rule concerns the use of C# 9.0 not pattern, when possible. dotnet_diagnostic.IDE0083.severity = warning -csharp_style_prefer_not_pattern = true:warning -# IDE0090 +## Options: +## csharp_style_prefer_not_pattern +## - true - Prefer to use the not pattern, when possible +## - false - Prefer not to use the not pattern. +## // csharp_style_prefer_not_pattern = true +## var y = o is not C c; +## +## // csharp_style_prefer_not_pattern = false +## var y = !(o is C c); +csharp_style_prefer_not_pattern = true + +## Use pattern matching (IsNot operator) (IDE0084) +## This style rule concerns the use of the Visual Basic 14.0 IsNot pattern, when possible. +dotnet_diagnostic.IDE0084.severity = none + +## Simplify new expression (IDE0090) +## This style rule concerns the use of C# 9.0 target-typed new expressions when the created type is apparent. dotnet_diagnostic.IDE0090.severity = warning -csharp_style_implicit_object_creation_when_type_is_apparent = false:warning -# IDE0100 +## Options: +## csharp_style_implicit_object_creation_when_type_is_apparent +## - true - Prefer target-typed new expressions when created type is apparent +## - false - Do not prefer target-typed new expressions +## // csharp_style_implicit_object_creation_when_type_is_apparent = true +## C c = new(); +## C c2 = new() { Field = 0 }; +## +## // csharp_style_implicit_object_creation_when_type_is_apparent = false +## C c = new C(); +## C c2 = new C() { Field = 0 }; +csharp_style_implicit_object_creation_when_type_is_apparent = false + +## Remove unnecessary equality operator (IDE0100) +## This style rule flags an unnecessary equality operator when comparing a non-constant Boolean expression with a constant true or false. +## // Code with violations +## if (x == true) { } +## if (M() != false) { } +## +## // Fixed code +## if (x) { } +## if (M()) { } dotnet_diagnostic.IDE0100.severity = warning -# IDE0110 +## Remove unnecessary discard (IDE0110) +## This rule flags unnecessary discard patterns. A discard pattern is unnecessary when used in a context where it has no effect. +## // Code with violations +## switch (o) +## { +## case int _: +## Console.WriteLine("Value was an int"); +## break; +## case string _: +## Console.WriteLine("Value was a string"); +## break; +## } +## +## // Fixed code +## switch (o) +## { +## case int: +## Console.WriteLine("Value was an int"); +## break; +## case string: +## Console.WriteLine("Value was a string"); +## break; +## } dotnet_diagnostic.IDE0110.severity = warning -dotnet_style_namespace_match_folder = true:warning -# IDE0150 -dotnet_diagnostic.IDE0150.severity = warning -csharp_style_prefer_null_check_over_type_check = false:warning +## Simplify LINQ expression (IDE0120) +## This rule flags overly complex LINQ expressions, specifically expressions that call xref:System.Linq.Enumerable.Where%60%601(System.Collections.Generic.IEnumerable{%60%600},System.Func{%60%600,System.Int32,System.Boolean})?displayProperty=nameWithType followed by one of the following methods: +## xref:System.Linq.Enumerable.Any%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.Count%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.First%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.FirstOrDefault%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.Last%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.LastOrDefault%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.Single%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## xref:System.Linq.Enumerable.SingleOrDefault%60%601(System.Collections.Generic.IEnumerable{%60%600}) +## Such expressions can be simplified by removing the call to xref:System.Linq.Enumerable.Where%60%601(System.Collections.Generic.IEnumerable{%60%600},System.Func{%60%600,System.Int32,System.Boolean}) and instead calling an overload of Any(), Count(), First(), FirstOrDefault(), Last(), LastOrDefault(), Single, or SingleOrDefault() that accepts a predicate function to filter the elements. +## // Code with violations. +## IEnumerable words = new List { "hello", "world", "!" }; +## var result = words.Where(x => x.Equals("hello")).Any(); +## +## // Fixed code. +## IEnumerable words = new List { "hello", "world", "!" }; +## var result = words.Any(x => x.Equals("hello")); +dotnet_diagnostic.IDE0120.severity = warning + +## Namespace does not match folder structure (IDE0130) +## This style rule uses the folder structure of the project to enforce namespace naming requirements. +## // Code with violations +## namespace Root.BadExample +## { +## class Example +## { +## public void M() +## { +## } +## } +## } +## +## // Fixed code +## namespace Root.Data +## { +## class Example +## { +## public void M() +## { +## } +## } +## } +dotnet_diagnostic.IDE0130.severity = warning + +## Options: +## dotnet_style_namespace_match_folder +## - true - Prefer namespace naming to match folder structure. +## - false - Disables the rule. +dotnet_style_namespace_match_folder = true + +## Simplify object creation (IDE0140) +## This style rule flags unnecessary type repetition in Visual Basic code. +dotnet_diagnostic.IDE0140.severity = none + +## Prefer null check over type check (IDE0150) +## This style rule flags use of the is {type} statement when is not null can be used instead. Similarly, it flags use of the is not {type} statement in favor of is null. Using is null or is not null improves code readability. +## // Violates IDE0150. +## if (numbers is not IEnumerable) ... +## +## // Fixed code. +## if (numbers is null) ... +dotnet_diagnostic.IDE0150.severity = suggestion + +## Options: +## csharp_style_prefer_null_check_over_type_check +## - true - Prefer null check over type check. +## - false - Disables the rule. +csharp_style_prefer_null_check_over_type_check = true -# IDE0160 and IDE0161 +## Use block-scoped namespace (IDE0160) +## Use file-scoped namespace (IDE0161) +## These rules apply to namespace declarations. For IDE0161 to report violations when block-scoped namespaces are used, you must set the associated option to file_scoped. +dotnet_diagnostic.IDE0160.severity = none dotnet_diagnostic.IDE0161.severity = warning -csharp_style_namespace_declarations = file_scoped:warning -# IDE0170 -dotnet_diagnostic.IDE0170.severity = none -csharp_style_prefer_extended_property_pattern = true:none +## Options: +## csharp_style_namespace_declarations +## - block_scoped - Namespace declarations should be block scoped. +## - file_scoped - Namespace declarations should be file scoped. +## // csharp_style_namespace_declarations = block_scoped +## using System; +## +## namespace Convention +## { +## class C +## { +## } +## } +## +## // csharp_style_namespace_declarations = file_scoped +## using System; +## +## namespace Convention; +## class C +## { +## } +csharp_style_namespace_declarations = file_scoped + +## Simplify property pattern (IDE0170) +## This style rule flags the use of a nested pattern in a property pattern. A nested pattern can be simplified to use an extended property pattern in which property subpatterns are used to reference nested members. Extended property patterns improve code readability. +## public record Point(int X, int Y); +## public record Segment(Point Start, Point End); +## +## // Violates IDE0170. +## static bool IsEndOnXAxis(Segment segment) => +## segment is { Start: { Y: 0 } } or { End: { Y: 0 } }; +## +## // Fixed code. +## static bool IsEndOnXAxis(Segment segment) => +## segment is { Start.Y: 0 } or { End.Y: 0 }; +dotnet_diagnostic.IDE0170.severity = suggestion + +## Options: +## csharp_style_prefer_extended_property_pattern +## - true - Prefer the extended property pattern. +## - false - Disables the rule. +csharp_style_prefer_extended_property_pattern = true + +## Use tuple to swap values (IDE0180) +## This style rule flags code that swaps two values using multiple lines of code instead of using a tuple. +## List numbers = new List() { 5, 6, 4 }; +## +## // Violates IDE0180. +## int temp = numbers[0]; +## numbers[0] = numbers[1]; +## numbers[1] = temp; +## +## // Fixed code. +## (numbers[1], numbers[0]) = (numbers[0], numbers[1]); +dotnet_diagnostic.IDE0180.severity = warning + +## Options: +## csharp_style_prefer_tuple_swap +## - true - Prefer using a tuple to swap two values. +## - false - Disables the rule. +csharp_style_prefer_tuple_swap = true + +## Remove unnecessary lambda expression (IDE0200) +## This rule flags the use of a lambda expression where it's unnecessary. Lambda expressions might be unnecessary when the following are all true: +## The expression includes a method invocation. +## The lambda expression has the same number and order of parameters as the method invocation. +## The method invocation has no side effects. +## The lambda expression isn't assigned to a non-delegate type. +## If the invocation is a generic method, the type arguments are supplied. +## The invoked method's return type can be converted to the lambda expression's return type. +## There's only one applicable method in the method group. +## // Code with violations. +## bool IsEven(int x) => x % 2 == 0; +## _ = new[] { 1, 2, 3 }.Where(n => IsEven(n)); +## +## // Fixed code. +## bool IsEven(int x) => x % 2 == 0; +## _ = new[] { 1, 2, 3 }.Where(IsEven); +dotnet_diagnostic.IDE0200.severity = suggestion + +## Options: +## csharp_style_prefer_method_group_conversion +## - true - Prefer to convert a lambda expression to a method group. +## - false - Disables the rule. +csharp_style_prefer_method_group_conversion = true + +## Convert to top-level statements (IDE0210) +## This rule flags the use of a Main method entry point in a project that could be converted to top-level statements instead. A candidate method must meet the following requirements: +## Is static. +## Is named Main. +## Has a method body. +## Has no type parameters. +## Is contained in a type that's not public, doesn't derive from another type or implement an interface, isn't a nested type, and has no attributes or documentation comments. +## // Code with violations. +## internal class Program +## { +## private static void Main(string[] args) +## { +## Console.WriteLine("Hello world."); +## } +## } +## +## // Fixed code. +## Console.WriteLine("Hello world."); +dotnet_diagnostic.IDE0210.severity = suggestion + +## Options: +## csharp_style_prefer_top_level_statements +## - true - Prefer top-level statements. +## - false - Disables the rule. +csharp_style_prefer_top_level_statements = false + +## Convert to 'Program.Main' style program (IDE0211) +## This rule flags the use of top-level statements instead of a Main method entry point in a project. +## // Code with violations (entire file). +## Console.WriteLine("Hello world."); +## +## // Fixed code. +## internal class Program +## { +## private static void Main(string[] args) +## { +## Console.WriteLine("Hello world."); +## } +## } +dotnet_diagnostic.IDE0211.severity = suggestion + +## Options: +## csharp_style_prefer_top_level_statements +## - true - Prefer top-level statements. +## - false - Disables the rule. +csharp_style_prefer_top_level_statements = false + +## Add explicit cast (IDE0220) +## This rule flags the absence of an explicit cast in a foreach loop when the compiler would add a hidden cast. For generic, or strongly typed, collections, forcing an explicit cast when the compiler would add a hidden cast can uncover the use of an incorrect type in the foreach statement. +## // Code with violations. +## var list = new List(); +## foreach (string item in list) { } +## +## // Fixed code. +## var list = new List(); +## foreach (string item in list.Cast()) +dotnet_diagnostic.IDE0220.severity = warning + +## Options: +## dotnet_style_prefer_foreach_explicit_cast_in_source +## - always - Prefer explicit casts in source code. +## - when_strongly_typed - Prefer explicit casts for strongly typed (generic) collections but not for legacy collections, such as xref:System.Collections.ArrayList. +dotnet_style_prefer_foreach_explicit_cast_in_source = always + +## Use UTF-8 string literal (IDE0230) +## This rule flags the use of a byte array (byte[]) where a UTF-8 string literal could be used instead. Using a UTF-8 string literal adds clarity to the declaration. +## // Code with violations. +## ReadOnlySpan _ = new byte[] { 65, 66, 67 }; +## +## // Fixed code. +## ReadOnlySpan _ = "ABC"u8; +dotnet_diagnostic.IDE0230.severity = suggestion + +## Options: +## csharp_style_prefer_utf8_string_literals +## - true - Prefer UTF-8 string literals to byte arrays. +## - false - Disables the rule. +csharp_style_prefer_utf8_string_literals = true -# IDE0180 -dotnet_diagnostic.IDE0180.severity = suggestion -csharp_style_prefer_tuple_swap = false:suggestion -csharp_style_prefer_method_group_conversion = true:silent -csharp_style_prefer_top_level_statements = true:silent -csharp_style_prefer_top_level_statements = true:silent -csharp_style_prefer_utf8_string_literals = true:suggestion +## Nullable directive is redundant (IDE0240) +## This rule flags places where a #nullable directive is redundant. For example: +## #nullable enable following another #nullable enable with no disablement in between. +## #nullable enable in a project where nullable context is already enabled and hasn't been disabled. +## #nullable restore following another #nullable restore with no nullability context change in between. +## #nullable restore in a place that already matches the project context. +## // Code with violations (in a project with enable). +## #nullable enable +## Console.WriteLine("Hello world."); +## +## // Fixed code. +## Console.WriteLine("Hello world."); +dotnet_diagnostic.IDE0240.severity = warning -# IDE1005 +## Nullable directive is unnecessary (IDE0241) +## This rule flags places where a #nullable directive is unnecessary. The directive is unnecessary where there are no reference types that would be impacted by the nullable context scope change. For example: +## #nullable enable in a project where nullable context is already enabled. +## #nullable disable in a project where nullable context is already disabled. +## #nullable disable for an enumeration. +## #nullable disable or #nullable restore at the end of a file that includes #nullable enable in a project where nullable context is disabled. +## // Code with violations (in a project with enable). +## #nullable disable +## enum Place +## { +## First, +## Second +## } +## +## // Fixed code. +## enum Place +## { +## First, +## Second +## } +dotnet_diagnostic.IDE0241.severity = warning + +## Struct can be made 'readonly' (IDE0250) +## This rule flags structs that aren't marked readonly when all their members are marked readonly. +## // Code with violations. +## struct S +## { +## readonly int i; +## } +## +## // Fixed code. +## readonly struct S +## { +## readonly int i; +## } +dotnet_diagnostic.IDE0250.severity = warning + +## Options: +## csharp_style_prefer_readonly_struct +## - true - Prefer to make a struct readonly when all its fields are readonly. +## - false - Disables the rule. +csharp_style_prefer_readonly_struct = true + +## Member can be made 'readonly' (IDE0251) +## This rule flags members of non-readonly structs that aren't marked readonly that could be marked as readonly. +## // Code with violations. +## struct S +## { +## void M() { } +## } +## +## // Fixed code. +## struct S +## { +## readonly void M() { } +## } +dotnet_diagnostic.IDE0251.severity = warning + +## Options: +## csharp_style_prefer_readonly_struct_member +## - true - Prefer to make struct members readonly. +## - false - Disables the rule. +csharp_style_prefer_readonly_struct_member = true + +## Use 'nameof' (IDE0280) +## This rule flags the use of a literal parameter name instead of the nameof expression in attributes such as xref:System.Diagnostics.CodeAnalysis.NotNullIfNotNullAttribute, xref:System.Diagnostics.CodeAnalysis.NotNullWhenAttribute, and xref:System.Runtime.CompilerServices.CallerArgumentExpressionAttribute that take a parameter name. +## // Code with violations. +## class C +## { +## void M([NotNullIfNotNull("input")] string? input) { } +## } +## +## // Fixed code. +## class C +## { +## void M([NotNullIfNotNull(nameof(input))] string? input) { } +## } +dotnet_diagnostic.IDE0280.severity = suggestion + +## Use conditional delegate call (IDE1005) +## This style rule concerns the use of the null-conditional operator (?.) when invoking a lambda expression, as opposed to performing a null check. dotnet_diagnostic.IDE1005.severity = suggestion -csharp_style_conditional_delegate_call = true:suggestion + +## Options: +## csharp_style_conditional_delegate_call +## - true - Prefer to use the conditional coalescing operator (?.) when invoking a lambda expression +## - false - Prefer to perform a null check before invoking a lambda expression +## // csharp_style_conditional_delegate_call = true +## func?.Invoke(args); +## +## // csharp_style_conditional_delegate_call = false +## if (func != null) { func(args); } +csharp_style_conditional_delegate_call = true ### CA ### +## Do not declare static members on generic types (CA1000) +## When a static member of a generic type is called, the type argument must be specified for the type. When a generic instance member that does not support inference is called, the type argument must be specified for the member. The syntax for specifying the type argument in these two cases is different and easily confused, as the following calls demonstrate: +## ' Shared method in a generic type. +## GenericType(Of Integer).SharedMethod() +## +## ' Generic instance method that does not support inference. +## someObject.GenericMethod(Of Integer)() +## // Static method in a generic type. +## GenericType.StaticMethod(); +## +## // Generic instance method that does not support inference. +## someObject.GenericMethod(); +## Generally, both of the prior declarations should be avoided so that the type argument does not have to be specified when the member is called. This results in a syntax for calling members in generics that is no different from the syntax for non-generics. dotnet_diagnostic.CA1000.severity = none + +## Types that own disposable fields should be disposable (CA1001) +## A class that declares an xref:System.IDisposable field indirectly owns an unmanaged resource. The class should implement the xref:System.IDisposable interface to dispose of the unmanaged resource that it owns once the resource is no longer in use. If the class does not directly own any unmanaged resources, it should not implement a finalizer. +## This rule respects types implementing xref:System.IAsyncDisposable?displayProperty=fullName as disposable types. dotnet_diagnostic.CA1001.severity = warning + +## Do not expose generic lists (CA1002) +## xref:System.Collections.Generic.List%601?displayProperty=fullName is a generic collection that's designed for performance and not inheritance. xref:System.Collections.Generic.List%601 does not contain virtual members that make it easier to change the behavior of an inherited class. The following generic collections are designed for inheritance and should be exposed instead of xref:System.Collections.Generic.List%601. +## xref:System.Collections.ObjectModel.Collection%601?displayProperty=fullName +## xref:System.Collections.ObjectModel.ReadOnlyCollection%601?displayProperty=fullName +## xref:System.Collections.ObjectModel.KeyedCollection%602?displayProperty=fullName +## xref:System.Collections.Generic.IList%601?displayProperty=fullName +## xref:System.Collections.Generic.ICollection%601?displayProperty=fullName dotnet_diagnostic.CA1002.severity = warning -dotnet_diagnostic.CA1003.severity = none + +## Use generic event handler instances (CA1003) +## Before .NET Framework 2.0, in order to pass custom information to the event handler, a new delegate had to be declared that specified a class that was derived from the xref:System.EventArgs?displayProperty=fullName class. In .NET Framework 2.0 and later versions, the generic xref:System.EventHandler%601?displayProperty=fullName delegate allows any class that's derived from xref:System.EventArgs to be used together with the event handler. +dotnet_diagnostic.CA1003.severity = warning + +## Avoid excessive parameters on generic types (CA1005) +## The more type parameters a generic type contains, the more difficult it is to know and remember what each type parameter represents. It is usually obvious with one type parameter, as in List, and in certain cases with two type parameters, as in Dictionary. If more than two type parameters exist, the difficulty becomes too great for most users (for example, TooManyTypeParameters in C# or TooManyTypeParameters(Of T, K, V) in Visual Basic). dotnet_diagnostic.CA1005.severity = none + +## Enums should have zero value (CA1008) +## The default value of an uninitialized enumeration, just like other value types, is zero. A non-flags-attributed enumeration should define a member that has the value of zero so that the default value is a valid value of the enumeration. If appropriate, name the member 'None' (or one of the additional permitted names). Otherwise, assign zero to the most frequently used member. By default, if the value of the first enumeration member is not set in the declaration, its value is zero. +## If an enumeration that has the xref:System.FlagsAttribute applied defines a zero-valued member, its name should be 'None' (or one of the additional permitted names) to indicate that no values have been set in the enumeration. Using a zero-valued member for any other purpose is contrary to the use of the xref:System.FlagsAttribute in that the AND and OR bitwise operators are useless with the member. This implies that only one member should be assigned the value zero. If multiple members that have the value zero occur in a flags-attributed enumeration, Enum.ToString() returns incorrect results for members that are not zero. dotnet_diagnostic.CA1008.severity = none -dotnet_diagnostic.CA1010.severity = warning + +## Collections should implement generic interface (CA1010) +## To broaden the usability of a collection, implement one of the generic collection interfaces. Then the collection can be used to populate generic collection types such as the following: +## xref:System.Collections.Generic.List%601?displayProperty=fullName +## xref:System.Collections.Generic.Queue%601?displayProperty=fullName +## xref:System.Collections.Generic.Stack%601?displayProperty=fullName +dotnet_diagnostic.CA1010.severity = suggestion + +## Abstract types should not have public constructors (CA1012) +## Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed. dotnet_diagnostic.CA1012.severity = warning + +## Mark assemblies with CLSCompliantAttribute (CA1014) +## The Common Language Specification (CLS) defines naming restrictions, data types, and rules to which assemblies must conform if they will be used across programming languages. Good design dictates that all assemblies explicitly indicate CLS compliance with xref:System.CLSCompliantAttribute. If the attribute is not present on an assembly, the assembly is not compliant. +## It is possible for a CLS-compliant assembly to contain types or type members that are not compliant. dotnet_diagnostic.CA1014.severity = none -dotnet_diagnostic.CA1016.severity = none + +## Mark assemblies with AssemblyVersionAttribute (CA1016) +## The identity of an assembly is composed of the following information: +## Assembly name +## Version number +## Culture +## Public key (for strongly named assemblies). +## .NET uses the version number to uniquely identify an assembly and to bind to types in strongly named assemblies. The version number is used together with version and publisher policy. By default, applications run only with the assembly version with which they were built. +dotnet_diagnostic.CA1016.severity = warning + +## Mark assemblies with Mark assemblies with ComVisibleAttribute (CA1017) +## The xref:System.Runtime.InteropServices.ComVisibleAttribute attribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for a whole assembly and then overridden for individual types and type members. If the attribute is not present, the contents of the assembly are visible to COM clients. dotnet_diagnostic.CA1017.severity = none -dotnet_diagnostic.CA1018.severity = warning + +## Mark attributes with AttributeUsageAttribute (CA1018) +## When you define a custom attribute, mark it by using xref:System.AttributeUsageAttribute to indicate where in the source code the custom attribute can be applied. The meaning and intended usage of an attribute will determine its valid locations in code. For example, you might define an attribute that identifies the person who is responsible for maintaining and enhancing each type in a library, and that responsibility is always assigned at the type level. In this case, compilers should enable the attribute on classes, enumerations, and interfaces, but should not enable it on methods, events, or properties. Organizational policies and procedures would dictate whether the attribute should be enabled on assemblies. +## The xref:System.AttributeTargets?displayProperty=fullName enumeration defines the targets that you can specify for a custom attribute. If you omit xref:System.AttributeUsageAttribute, your custom attribute will be valid for all targets, as defined by the All value of xref:System.AttributeTargets enumeration. +dotnet_diagnostic.CA1018.severity = error + +## Define accessors for attribute arguments (CA1019) +## Attributes can define mandatory arguments that must be specified when you apply the attribute to a target. These are also known as positional arguments because they are supplied to attribute constructors as positional parameters. For every mandatory argument, the attribute should also provide a corresponding read-only property so that the value of the argument can be retrieved at execution time. This rule checks that for each constructor parameter, you have defined the corresponding property. +## Attributes can also define optional arguments, which are also known as named arguments. These arguments are supplied to attribute constructors by name and should have a corresponding read/write property. +## For mandatory and optional arguments, the corresponding properties and constructor parameters should use the same name but different casing. Properties use Pascal casing, and parameters use camel casing. dotnet_diagnostic.CA1019.severity = warning + +## Avoid out parameters (CA1021) +## Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods with multiple return values. Also, the difference between out and ref parameters is not widely understood. +## When a reference type is passed "by reference," the method intends to use the parameter to return a different instance of the object. Passing a reference type by reference is also known as using a double pointer, pointer to a pointer, or double indirection. By using the default calling convention, which is pass "by value," a parameter that takes a reference type already receives a pointer to the object. The pointer, not the object to which it points, is passed by value. Pass by value means that the method cannot change the pointer to have it point to a new instance of the reference type. However, it can change the contents of the object to which it points. For most applications this is sufficient and yields the desired behavior. +## If a method must return a different instance, use the return value of the method to accomplish this. See the xref:System.String?displayProperty=fullName class for a variety of methods that operate on strings and return a new instance of a string. When this model is used, the caller must decide whether the original object is preserved. +## Although return values are commonplace and heavily used, the correct application of out and ref parameters requires intermediate design and coding skills. Library architects who design for a general audience should not expect users to become proficient in working with out or ref parameters. dotnet_diagnostic.CA1021.severity = warning + +## Use properties where appropriate (CA1024) +## In most cases, properties represent data and methods perform actions. Properties are accessed like fields, which makes them easier to use. A method is a good candidate to become a property if one of these conditions is present: +## The method takes no arguments and returns the state information of an object. +## The method accepts a single argument to set some part of the state of an object. dotnet_diagnostic.CA1024.severity = suggestion + +## Mark enums with FlagsAttribute (CA1027) +## An enumeration is a value type that defines a set of related named constants. Apply xref:System.FlagsAttribute to an enumeration when its named constants can be meaningfully combined. For example, consider an enumeration of the days of the week in an application that keeps track of which day's resources are available. If the availability of each resource is encoded by using the enumeration that has xref:System.FlagsAttribute present, any combination of days can be represented. Without the attribute, only one day of the week can be represented. +## For fields that store combinable enumerations, the individual enumeration values are treated as groups of bits in the field. Therefore, such fields are sometimes referred to as bit fields. To combine enumeration values for storage in a bit field, use the Boolean conditional operators. To test a bit field to determine whether a specific enumeration value is present, use the Boolean logical operators. For a bit field to store and retrieve combined enumeration values correctly, each value that is defined in the enumeration must be a power of two. Unless this is so, the Boolean logical operators will not be able to extract the individual enumeration values that are stored in the field. dotnet_diagnostic.CA1027.severity = none -dotnet_diagnostic.CA1028.severity = warning + +## Enum storage should be Int32 (CA1028) +## An enumeration is a value type that defines a set of related named constants. By default, the xref:System.Int32?displayProperty=fullName data type is used to store the constant value. Even though you can change this underlying type, it is not necessary or recommended for most scenarios. No significant performance gain is achieved by using a data type that is smaller than xref:System.Int32. If you cannot use the default data type, you should use one of the Common Language System (CLS)-compliant integral types, xref:System.Byte, xref:System.Int16, xref:System.Int32, or xref:System.Int64 to make sure that all values of the enumeration can be represented in CLS-compliant programming languages. +dotnet_diagnostic.CA1028.severity = suggestion + +## Use events where appropriate (CA1030) +## This rule detects methods that have names that ordinarily would be used for events. Events follow the Observer or Publish-Subscribe design pattern; they are used when a state change in one object must be communicated to other objects. If a method gets called in response to a clearly defined state change, the method should be invoked by an event handler. Objects that call the method should raise events instead of calling the method directly. +## Some common examples of events are found in user interface applications where a user action such as clicking a button causes a segment of code to execute. The .NET event model is not limited to user interfaces. It should be used anywhere you must communicate state changes to one or more objects. dotnet_diagnostic.CA1030.severity = none + +## Do not catch general exception types (CA1031) +## General exceptions should not be caught. dotnet_diagnostic.CA1031.severity = none -dotnet_diagnostic.CA1032.severity = none + +## Implement standard exception constructors (CA1032) +## Exception types must implement the following three public constructors: +## public NewException() +## public NewException(string) +## public NewException(string, Exception) +## Failure to provide the full set of constructors can make it difficult to correctly handle exceptions. For example, the constructor that has the signature NewException(string, Exception) is used to create exceptions that are caused by other exceptions. Without this constructor, you can't create and throw an instance of your custom exception that contains an inner (nested) exception, which is what managed code should do in such a situation. +## For more information, see CA2229: Implement serialization constructors. +dotnet_diagnostic.CA1032.severity = warning + +## Interface methods should be callable by child types (CA1033) +## Consider a base type that explicitly implements a public interface method. A type that derives from the base type can access the inherited interface method only through a reference to the current instance (this in C#) that is cast to the interface. If the derived type reimplements (explicitly) the inherited interface method, the base implementation can no longer be accessed. The call through the current instance reference will invoke the derived implementation; this causes recursion and an eventual stack overflow. +## This rule does not report a violation for an explicit implementation of xref:System.IDisposable.Dispose%2A?displayProperty=fullName when an externally visible Close() or System.IDisposable.Dispose(Boolean) method is provided. dotnet_diagnostic.CA1033.severity = none -dotnet_diagnostic.CA1034.severity = none -dotnet_diagnostic.CA1036.severity = silent -dotnet_diagnostic.CA1040.severity = none -dotnet_diagnostic.CA1041.severity = suggestion -dotnet_diagnostic.CA1043.severity = none + +## Nested types should not be visible (CA1034) +## A nested type is a type declared within the scope of another type. Nested types are useful for encapsulating private implementation details of the containing type. Used for this purpose, nested types should not be externally visible. +## Do not use externally visible nested types for logical grouping or to avoid name collisions; instead, use namespaces. +## Nested types include the notion of member accessibility, which some programmers do not understand clearly. +## Protected types can be used in subclasses and nested types in advance customization scenarios. +dotnet_diagnostic.CA1034.severity = silent + +## Override methods on comparable types (CA1036) +## Types that define a custom sort order implement the xref:System.IComparable interface. The xref:System.IComparable.CompareTo%2A method returns an integer value that indicates the correct sort order for two instances of the type. This rule identifies types that set a sort order. Setting a sort order implies that the ordinary meaning of equality, inequality, less-than, and greater-than don't apply. When you provide an implementation of xref:System.IComparable, you must usually also override xref:System.Object.Equals%2A so that it returns values that are consistent with xref:System.IComparable.CompareTo%2A. If you override xref:System.Object.Equals%2A and are coding in a language that supports operator overloads, you should also provide operators that are consistent with xref:System.Object.Equals%2A. +dotnet_diagnostic.CA1036.severity = warning + +## Avoid empty interfaces (CA1040) +## Interfaces define members that provide a behavior or usage contract. The functionality that is described by the interface can be adopted by any type, regardless of where the type appears in the inheritance hierarchy. A type implements an interface by providing implementations for the members of the interface. An empty interface does not define any members. Therefore, it does not define a contract that can be implemented. +## If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface. +dotnet_diagnostic.CA1040.severity = silent + +## Provide ObsoleteAttribute message (CA1041) +## xref:System.ObsoleteAttribute is used to mark deprecated library types and members. Library consumers should avoid the use of any type or member that is marked obsolete. This is because it might not be supported and will eventually be removed from later versions of the library. When a type or member marked by using xref:System.ObsoleteAttribute is compiled, the xref:System.ObsoleteAttribute.Message%2A property of the attribute is displayed. This gives the user information about the obsolete type or member. This information generally includes how long the obsolete type or member will be supported by the library designers and the preferred replacement to use. +dotnet_diagnostic.CA1041.severity = warning + +## Use integral or string argument for indexers (CA1043) +## Indexers, that is, indexed properties, should use integer or string types for the index. These types are typically used for indexing data structures and increase the usability of the library. Use of the xref:System.Object type should be restricted to those cases where the specific integer or string type cannot be specified at design time. If the design requires other types for the index, reconsider whether the type represents a logical data store. If it does not represent a logical data store, use a method. +dotnet_diagnostic.CA1043.severity = warning + +## Properties should not be write only (CA1044) +## Get accessors provide read access to a property and set accessors provide write access. Although it is acceptable and often necessary to have a read-only property, the design guidelines prohibit the use of write-only properties. This is because letting a user set a value and then preventing the user from viewing the value does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness. dotnet_diagnostic.CA1044.severity = warning -dotnet_diagnostic.CA1045.severity = warning -dotnet_diagnostic.CA1046.severity = suggestion + +## Do not pass types by reference (CA1045) +## Passing types by reference (using out or ref) requires experience with pointers, understanding how value types and reference types differ, and handling methods that have multiple return values. Also, the difference between out and ref parameters is not widely understood. +## When a reference type is passed "by reference," the method intends to use the parameter to return a different instance of the object. (Passing a reference type by reference is also known as using a double pointer, pointer to a pointer, or double indirection.) Using the default calling convention, which is pass "by value," a parameter that takes a reference type already receives a pointer to the object. The pointer, not the object to which it points, is passed by value. Passing by value means that the method cannot change the pointer to have it point to a new instance of the reference type, but can change the contents of the object to which it points. For most applications this is sufficient and yields the behavior that you want. +## If a method must return a different instance, use the return value of the method to accomplish this. See the xref:System.String?displayProperty=fullName class for a variety of methods that operate on strings and return a new instance of a string. By using this model, it is left to the caller to decide whether the original object is preserved. +## Although return values are commonplace and heavily used, the correct application of out and ref parameters requires intermediate design and coding skills. Library architects who design for a general audience should not expect users to become proficient in working with out or ref parameters. +## [!NOTE] +## When you work with parameters that are large structures, the additional resources that are required to copy these structures could cause a performance effect when you pass by value. In these cases, you might consider using ref or out parameters. +dotnet_diagnostic.CA1045.severity = suggestion + +## Do not overload operator equals on reference types (CA1046) +## For reference types, the default implementation of the equality operator is almost always correct. By default, two references are equal only if they point to the same object. +dotnet_diagnostic.CA1046.severity = none + +## Do not declare protected members in sealed types (CA1047) +## Types declare protected members so that inheriting types can access or override the member. By definition, you cannot inherit from a sealed type, which means that protected methods on sealed types cannot be called. +## The C# compiler issues a warning for this error. dotnet_diagnostic.CA1047.severity = warning + +## Declare types in namespaces (CA1050) +## Types are declared in namespaces to prevent name collisions, and as a way to organize related types in an object hierarchy. Types that are outside any named namespace are in a global namespace that cannot be referenced in code. dotnet_diagnostic.CA1050.severity = warning + +## Do not declare visible instance fields (CA1051) +## The primary use of a field should be as an implementation detail. Fields should be private or internal and should be exposed by using properties. It's as easy to access a property as it is to access a field, and the code in the accessors of a property can change as the features of the type expand without introducing breaking changes. +## Properties that just return the value of a private or internal field are optimized to perform on par with accessing a field; the performance gain from using externally visible fields instead of properties is minimal. Externally visible refers to public, protected, and protected internal (Public, Protected, and Protected Friend in Visual Basic) accessibility levels. +## Additionally, public fields cannot be protected by Link demands. (Link demands don't apply to .NET Core apps.) dotnet_diagnostic.CA1051.severity = warning -dotnet_diagnostic.CA1052.severity = none + +## Static holder types should be Static or NotInheritable (CA1052) +## Rule CA1052 assumes that a type that contains only static members is not designed to be inherited, because the type does not provide any functionality that can be overridden in a derived type. A type that is not meant to be inherited should be marked with the static modifier in C# to prohibit its use as a base type. Additionally, its default constructor should be removed. In Visual Basic, the class should be converted to a module. +## This rule does not fire for abstract classes or classes that have a base class. However, the rule does fire for classes that support an empty interface. +## [!NOTE] +## In the latest analyzer implementation of this rule, it also encompasses the functionality of rule CA1053. +dotnet_diagnostic.CA1052.severity = warning + +## Static holder types should not have default constructors (CA1053) +## The default constructor is unnecessary because calling static members does not require an instance of the type. Also, because the type does not have non-static members, creating an instance does not provide access to any of the type's members. dotnet_diagnostic.CA1053.severity = none + +## URI parameters should not be strings (CA1054) +## This rule splits the parameter name into tokens based on the camel casing convention and checks whether each token equals "uri", "Uri", "urn", "Urn", "url", or "Url". If there's a match, the rule assumes that the parameter represents a uniform resource identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the xref:System.Uri class, which provides these services in a safe and secure manner. dotnet_diagnostic.CA1054.severity = suggestion + +## URI return values should not be strings (CA1055) +## This rule splits the method name into tokens based on the Pascal casing convention and checks whether each token equals "uri", "Uri", "urn", "Urn", "url", or "Url". If there's a match, the rule assumes that the method returns a uniform resource identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The xref:System.Uri?displayProperty=fullName class provides these services in a safe and secure manner. dotnet_diagnostic.CA1055.severity = suggestion + +## URI properties should not be strings (CA1056) +## This rule splits the property name into tokens based on the Pascal casing convention and checks whether each token equals "uri", "Uri", "urn", "Urn", "url", or "Url". If there's a match, the rule assumes that the property represents a uniform resource identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The xref:System.Uri?displayProperty=fullName class provides these services in a safe and secure manner. dotnet_diagnostic.CA1056.severity = suggestion -dotnet_diagnostic.CA1058.severity = warning + +## Types should not extend certain base types (CA1058) +## Exceptions should derive from xref:System.Exception?displayProperty=fullName or one of its subclasses in the xref:System namespace. +## Do not create a subclass of xref:System.Xml.XmlDocument if you want to create an XML view of an underlying object model or data source. +dotnet_diagnostic.CA1058.severity = none + +## Move P/Invokes to NativeMethods class (CA1060) +## Platform Invocation methods, such as those that are marked by using the xref:System.Runtime.InteropServices.DllImportAttribute?displayProperty=fullName attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be in one of the following classes: +## NativeMethods - This class does not suppress stack walks for unmanaged code permission. (xref:System.Security.SuppressUnmanagedCodeSecurityAttribute?displayProperty=fullName must not be applied to this class.) This class is for methods that can be used anywhere because a stack walk will be performed. +## SafeNativeMethods - This class suppresses stack walks for unmanaged code permission. (xref:System.Security.SuppressUnmanagedCodeSecurityAttribute?displayProperty=fullName is applied to this class.) This class is for methods that are safe for anyone to call. Callers of these methods are not required to perform a full security review to make sure that the usage is secure because the methods are harmless for any caller. +## UnsafeNativeMethods - This class suppresses stack walks for unmanaged code permission. (xref:System.Security.SuppressUnmanagedCodeSecurityAttribute?displayProperty=fullName is applied to this class.) This class is for methods that are potentially dangerous. Any caller of these methods must perform a full security review to make sure that the usage is secure because no stack walk will be performed. +## These classes are declared as internal (Friend in Visual Basic) and declare a private constructor to prevent new instances from being created. The methods in these classes should be static and internal (Shared and Friend in Visual Basic). dotnet_diagnostic.CA1060.severity = none + +## Do not hide base class methods (CA1061) +## A method in a base type is hidden by an identically named method in a derived type when the parameter signature of the derived method differs only by types that are more weakly derived than the corresponding types in the parameter signature of the base method. dotnet_diagnostic.CA1061.severity = warning -dotnet_diagnostic.CA1062.severity = suggestion -dotnet_diagnostic.CA1063.severity = none + +## Validate arguments of public methods (CA1062) +## All reference arguments that are passed to externally visible methods should be checked against null. If appropriate, throw an xref:System.ArgumentNullException when the argument is null. +## If a method can be called from an unknown assembly because it is declared public or protected, you should validate all parameters of the method. If the method is designed to be called only by known assemblies, mark the method internal and apply the xref:System.Runtime.CompilerServices.InternalsVisibleToAttribute attribute to the assembly that contains the method. +dotnet_diagnostic.CA1062.severity = warning + +## Implement IDisposable correctly (CA1063) +## All xref:System.IDisposable types should implement the Dispose pattern correctly. +dotnet_diagnostic.CA1063.severity = suggestion + +## Exceptions should be public (CA1064) +## An internal exception is only visible inside its own internal scope. After the exception falls outside the internal scope, only the base exception can be used to catch the exception. If the internal exception is inherited from xref:System.Exception, xref:System.SystemException, or xref:System.ApplicationException, the external code will not have sufficient information to know what to do with the exception. +## But, if the code has a public exception that later is used as the base for an internal exception, it is reasonable to assume the code further out will be able to do something intelligent with the base exception. The public exception will have more information than what is provided by xref:System.Exception, xref:System.SystemException, or xref:System.ApplicationException. dotnet_diagnostic.CA1064.severity = warning -dotnet_diagnostic.CA1065.severity = warning + +## Do not raise exceptions in unexpected locations (CA1065) +## Methods that are not expected to throw exceptions can be categorized as follows: +## Property Get Methods +## Event Accessor Methods +## Equals Methods +## GetHashCode Methods +## ToString Methods +## Static Constructors +## Finalizers +## Dispose Methods +## Equality Operators +## Implicit Cast Operators +## The following sections discuss these method types. +dotnet_diagnostic.CA1065.severity = error + +## Implement IEquatable when overriding Equals (CA1066) +## A value type overriding xref:System.Object.Equals%2A method indicates that it supports comparing two instances of the type for value equality. Consider implementing the xref:System.IEquatable%601 interface to support strongly typed tests for equality. This ensures that callers performing equality checks invoke the strongly typed xref:System.IEquatable%601.Equals%2A?displayProperty=fullName method and avoid boxing the argument, improving performance. For more information, see here. +## Your xref:System.IEquatable%601.Equals%2A?displayProperty=fullName implementation should return results that are consistent with xref:System.Object.Equals%2A. +dotnet_diagnostic.CA1066.severity = warning + +## Override Equals when implementing IEquatable (CA1067) +## A type implementing xref:System.IEquatable%601 interface indicates that it supports comparing two instances of the type for equality. You should also override the base class implementations of xref:System.Object.Equals%2A and xref:System.Object.GetHashCode methods so that their behavior is consistent with that of the xref:System.IEquatable%601.Equals%2A?displayProperty=fullName implementation. See here for more details. +## Your xref:System.Object.Equals%2A implementation should return results that are consistent with xref:System.IEquatable%601.Equals%2A?displayProperty=fullName implementation. dotnet_diagnostic.CA1067.severity = warning + +## CancellationToken parameters must come last (CA1068) +## Methods that perform long running operations or asynchronous operations and are cancelable normally take a cancellation token parameter. Each cancellation token has a xref:System.Threading.CancellationTokenSource that creates the token and uses it for cancelable computations. It is common practice to have a long chain of method calls that pass around the cancellation token from the callers to the callees. Hence, a large number of methods that take part in a cancelable computation end up having a cancellation token parameter. However, the cancellation token itself is not usually relevant to the core functionality of a majority of these methods. It's considered a good API design practice to have such parameters be the last parameter in the list. dotnet_diagnostic.CA1068.severity = warning + +## Enums should not have duplicate values (CA1069) +## Every enum member should either have a unique constant value or be explicitly assigned with a prior member in the enum to indicate explicit intent of sharing value. For example: +## enum E +## { +## Field1 = 1, +## AnotherNameForField1 = Field1, // This is fine +## Field2 = 2, +## Field3 = 2, // CA1069: This is not fine. Either assign a different constant value or 'Field2' to indicate explicit intent of sharing value. +## } +## This rule helps in catching functional bugs introduced from the following scenarios: +## Accidental typing mistakes, where the user accidentally typed the same constant value for multiple members. +## Copy paste mistakes, where the user copied an existing member definition, then renamed the member but forgot to change the value. +## Merge resolution from multiple branches, where a new member was added with a different name but the same value in different branches. dotnet_diagnostic.CA1069.severity = warning -dotnet_diagnostic.CA1200.severity = none + +## Do not declare event fields as virtual (CA1070) +## Follow these .NET design guidelines to raise base class events in derived classes. Do not declare virtual events in a base class. Overridden events in a derived class have undefined behavior. The C# compiler does not handle this correctly and it is unpredictable whether a subscriber to the derived event will actually be subscribing to the base class event. +## using System; +## public class C +## { +## // CA1070: Event 'ThresholdReached' should not be declared virtual. +## public virtual event EventHandler ThresholdReached; +## } +dotnet_diagnostic.CA1070.severity = warning + +## Avoid using cref tags with a prefix (CA1200) +## The cref attribute in an XML documentation tag means "code reference". It specifies that the inner text of the tag is a code element, such as a type, method, or property. Avoid using cref tags with prefixes, because it prevents the compiler from verifying references. It also prevents the Visual Studio integrated development environment (IDE) from finding and updating these symbol references during refactorings. It is recommended that you use the full syntax without prefixes to reference symbol names in cref tags. +dotnet_diagnostic.CA1200.severity = suggestion + +## Do not pass literals as localized parameters (CA1303) +## String literals that are embedded in source code are difficult to localize. dotnet_diagnostic.CA1303.severity = none + +## Specify CultureInfo (CA1304) +## When a xref:System.Globalization.CultureInfo or xref:System.IFormatProvider?displayProperty=nameWithType object is not supplied, the default value that is supplied by the overloaded member might not have the effect that you want in all locales. Also, .NET members choose default culture and formatting based on assumptions that might not be correct for your code. To ensure the code works as expected for your scenarios, you should supply culture-specific information according to the following guidelines: +## If the value will be displayed to the user, use the current culture. See xref:System.Globalization.CultureInfo.CurrentCulture%2A?displayProperty=nameWithType. +## If the value will be stored and accessed by software, that is, persisted to a file or database, use the invariant culture. See xref:System.Globalization.CultureInfo.InvariantCulture%2A?displayProperty=nameWithType. +## If you do not know the destination of the value, have the data consumer or provider specify the culture. +## Even if the default behavior of the overloaded member is appropriate for your needs, it is better to explicitly call the culture-specific overload so that your code is self-documenting and more easily maintained. +## [!NOTE] +## xref:System.Globalization.CultureInfo.CurrentUICulture%2A?displayProperty=nameWithType is used only to retrieve localized resources by using an instance of the xref:System.Resources.ResourceManager?displayProperty=nameWithType class. dotnet_diagnostic.CA1304.severity = none + +## Specify IFormatProvider (CA1305) +## When a xref:System.Globalization.CultureInfo?displayProperty=nameWithType or xref:System.IFormatProvider object is not supplied, the default value that's supplied by the overloaded member might not have the effect that you want in all locales. Also, .NET members choose default culture and formatting based on assumptions that might not be correct for your code. To make sure that the code works as expected for your scenarios, you should supply culture-specific information according to the following guidelines: +## If the value will be displayed to the user, use the current culture. See xref:System.Globalization.CultureInfo.CurrentCulture%2A?displayProperty=nameWithType. +## If the value will be stored and accessed by software (persisted to a file or database), use the invariant culture. See xref:System.Globalization.CultureInfo.InvariantCulture%2A?displayProperty=nameWithType. +## If you don't know the destination of the value, have the data consumer or provider specify the culture. +## Even if the default behavior of the overloaded member is appropriate for your needs, it's better to explicitly call the culture-specific overload so that your code is self-documenting and more easily maintained. dotnet_diagnostic.CA1305.severity = none -dotnet_diagnostic.CA1307.severity = warning -dotnet_diagnostic.CA1308.severity = suggestion -dotnet_diagnostic.CA1309.severity = suggestion -dotnet_diagnostic.CA1310.severity = suggestion -dotnet_diagnostic.CA1401.severity = warning -dotnet_diagnostic.CA1416.severity = warning -dotnet_diagnostic.CA1417.severity = warning -dotnet_diagnostic.CA1418.severity = warning + +## Specify StringComparison for clarity (CA1307) +## Many string compare operations provide an overload that accepts a xref:System.StringComparison enumeration value as a parameter. +## Whenever an overload exists that takes a xref:System.StringComparison parameter, it should be used instead of an overload that does not take this parameter. By explicitly setting this parameter, your code is often made clearer and easier to maintain. For more information, see Specifying string comparisons explicitly. +## [!NOTE] +## This rule does not consider the default xref:System.StringComparison value used by the comparison method. Hence, it can be potentially noisy for methods that use the Ordinal string comparison by default and the user intended to use this default compare mode. +## If you only want to see violations only for known string methods that use culture-specific string comparison by default, please use CA1310: Specify StringComparison for correctness instead. +dotnet_diagnostic.CA1307.severity = none + +## Normalize strings to uppercase (CA1308) +## Strings should be normalized to uppercase. A small group of characters, when they are converted to lowercase, cannot make a round trip. To make a round trip means to convert the characters from one locale to another locale that represents character data differently, and then to accurately retrieve the original characters from the converted characters. +dotnet_diagnostic.CA1308.severity = none + +## Use ordinal StringComparison (CA1309) +## Many string operations, most importantly the xref:System.String.Compare%2A?displayProperty=fullName and xref:System.String.Equals%2A?displayProperty=fullName methods, now provide an overload that accepts a xref:System.StringComparison?displayProperty=fullName enumeration value as a parameter. +## When you specify either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, the string comparison is non-linguistic. That is, the features that are specific to the natural language are ignored when comparison decisions are made. Ignoring natural language features means the decisions are based on simple byte comparisons and not on casing or equivalence tables that are parameterized by culture. As a result, by explicitly setting the parameter to either the StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, increases correctness, and becomes more reliable. +dotnet_diagnostic.CA1309.severity = none + +## Specify StringComparison for correctness (CA1310) +## A string comparison method that uses culture-specific string comparison by default can have potentially unintentional runtime behavior that does not match user intent. It is recommended that you use the overload with the xref:System.StringComparison parameter for correctness and clarity of intent. +## This rule flags string comparison methods that use the culture-specific xref:System.StringComparison value by default. For more information, see String comparisons that use the current culture. +## [!NOTE] +## If you want to see violations for all string comparison methods, regardless of the default string comparison used by the method, please use CA1307: Specify StringComparison for clarity instead. +dotnet_diagnostic.CA1310.severity = none + +## Specify a culture or use an invariant version (CA1311) +## Specify a culture or use an invariant culture to avoid implicit dependency on the current culture when calling ToUpper or ToLower. Using an invariant culture yields consistent results regardless of the culture of an application. +dotnet_diagnostic.CA1311.severity = none + +## P/Invokes should not be visible (CA1401) +## Methods that are marked with the xref:System.Runtime.InteropServices.DllImportAttribute attribute (or methods that are defined by using the Declare keyword in Visual Basic) use Platform Invocation Services to access unmanaged code. Such methods should not be exposed. By keeping these methods private or internal, you make sure that your library cannot be used to breach security by allowing callers access to unmanaged APIs that they could not call otherwise. +dotnet_diagnostic.CA1401.severity = none + +## Validate platform compatibility (CA1416) +## .NET 5 added new attributes, xref:System.Runtime.Versioning.SupportedOSPlatformAttribute and xref:System.Runtime.Versioning.UnsupportedOSPlatformAttribute, to annotate platform-specific APIs. Both attributes can be instantiated with or without version numbers as part of the platform name. They can also be applied multiple times with different platforms. +## An unannotated API is considered to work on all operating system (OS) platforms. +## An API marked with [SupportedOSPlatform("platformName")] is considered to be portable to the specified OS platforms only. If the platform is a subset of another platform, the attribute implies that that platform is also supported. +## An API marked with [UnsupportedOSPlatform("platformName")] is considered to be unsupported on the specified OS platforms. If the platform is a subset of another platform, the attribute implies that that platform is also unsupported. +## You can combine [SupportedOSPlatform] and [UnsupportedOSPlatform] attributes on a single API. In this case, the following rules apply: +## Allow list. If the lowest version for each OS platform is a [SupportedOSPlatform] attribute, the API is considered to only be supported by the listed platforms and unsupported by all other platforms. The list can have an [UnsupportedOSPlatform] attribute with the same platform, but only with a higher version, which denotes that the API is removed from that version. +## Deny list. If the lowest version for each OS platform is an [UnsupportedOSPlatform] attribute, then the API is considered to only be unsupported by the listed platforms and supported by all other platforms. The list can have a [SupportedOSPlatform] attribute with the same platform, but only with a higher version, which denotes that the API is supported since that version. +## Inconsistent list. If the lowest version for some platforms is [SupportedOSPlatform] but [UnsupportedOSPlatform] for other platforms, this combination is considered inconsistent. Some annotations on the API are ignored. In the future, we may introduce an analyzer that produces a warning in case of inconsistency. +## If you access an API annotated with these attributes from the context of a different platform, you can see CA1416 violations. +dotnet_diagnostic.CA1416.severity = none + +## Do not use OutAttribute on string parameters for P/Invokes (CA1417) +## The .NET runtime automatically performs string interning. If an interned string marked with xref:System.Runtime.InteropServices.OutAttribute is passed by value to a P/Invoke, the runtime can be destabilized. +dotnet_diagnostic.CA1417.severity = none + +## Validate platform compatibility (CA1418) +## The platform compatibility attributes derived from xref:System.Runtime.Versioning.OSPlatformAttribute use string literals for operating system (OS) platform names with an optional version part. The string should consist of a known platform name and either no version part or a valid version part. +## The known platform names list is populated from two places: +## The PlatformName part of xref:System.OperatingSystem guard methods named OperatingSystem.Is[VersionAtLeast](). For example, guard method xref:System.OperatingSystem.IsWindows?displayProperty=nameWithType adds Windows to the known platform names list. +## The project's MSBuild item group of SupportedPlatform items, including the default MSBuild SupportedPlatforms list. This is the project specific knowledge of known platforms. It allows class library authors to add more platforms into the known platforms list. For example: +## +## +## +## If the platform string contains a version part, it should be a valid xref:System.Version with the following format: major.minor[.build[.revision]]. +dotnet_diagnostic.CA1418.severity = none + +## Provide a parameterless constructor that is as visible as the containing type for concrete types derived from 'System.Runtime.InteropServices.SafeHandle' (CA1419) +## Providing a public parameterless constructor for a type derived from xref:System.Runtime.InteropServices.SafeHandle enables better performance and usage with source-generated interop solutions. dotnet_diagnostic.CA1419.severity = warning -dotnet_diagnostic.CA1501.severity = warning -dotnet_diagnostic.CA1502.severity = warning -dotnet_diagnostic.CA1505.severity = warning -dotnet_diagnostic.CA1506.severity = warning + +## Property, type, or attribute requires runtime marshalling (CA1420) +## Using features that require runtime marshalling when runtime marshalling is disabled will result in run-time exceptions. +dotnet_diagnostic.CA1420.severity = none + +## Method uses runtime marshalling when DisableRuntimeMarshallingAttribute is applied (CA1421) +## If a method uses runtime marshalling when runtime marshalling is disabled, it can cause unexpected behavior differences at run time due to different expectations of a type's native layout. +dotnet_diagnostic.CA1421.severity = none + +## Validate platform compatibility - obsoleted APIs (CA1422) +## Calling an API that's obsolete in a given OS (version) from a call site that's reachable from that OS (version) is not recommended. Consider calling a non-obsolete API instead, or guarding against calling the obsolete API on affected operating systems. +dotnet_diagnostic.CA1422.severity = none + +## Avoid excessive inheritance (CA1501) +## Deeply nested type hierarchies can be difficult to follow, understand, and maintain. This rule limits analysis to hierarchies in the same module. +## You can configure this rule in the following ways: +## By default, the rule excludes types from the System namespace. You can configure the rule to exclude other types or namespaces as well. +## You can configure the inheritance tree depth at which this rule fires. +dotnet_diagnostic.CA1501.severity = none + +## Avoid excessive complexity (CA1502) +## Cyclomatic complexity measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches. A low cyclomatic complexity generally indicates a method that is easy to understand, test, and maintain. The cyclomatic complexity is calculated from a control flow graph of the method and is given as follows: +## cyclomatic complexity = the number of edges - the number of nodes + 1 +## A node represents a logic branch point and an edge represents a line between nodes. +## The rule reports a violation when the cyclomatic complexity of a method is more than 25. However, you can configure the threshold and also specify other kinds of symbols that the rule should analyze. +## You can learn more about code metrics at Measure complexity of managed code. +dotnet_diagnostic.CA1502.severity = none + +## Avoid unmaintainable code (CA1505) +## The rule reports a violation when the maintainability index of a type, method, field, property, or event is less than 10. However, you can configure the threshold. +## The maintainability index is calculated by using the following metrics: lines of code, program volume, and cyclomatic complexity. (Program volume is a measure of the difficulty of understanding of a type or method that's based on the number of operators and operands in the code. Cyclomatic complexity is a measure of the structural complexity of the type or method. You can learn more about code metrics at Measure complexity and maintainability of managed code. +## A low maintainability index indicates that a type or method is probably difficult to maintain and would be a good candidate to redesign. +dotnet_diagnostic.CA1505.severity = none + +## Avoid excessive class coupling (CA1506) +## This rule measures class coupling by counting the number of unique type references that a type, method, field, property, or event contains. The default coupling threshold is 95 for types and 40 for other symbol kinds, and the thresholds are configurable. +## Types, methods, and other symbols that have a high degree of class coupling can be difficult to maintain. It's a good practice to have types, methods, and other symbols that exhibit low coupling and high cohesion. +dotnet_diagnostic.CA1506.severity = none + +## Use nameof in place of string (CA1507) +## Rule CA1507 flags the use of a string literal as an argument to a method or constructor where a nameof (NameOf in Visual Basic) expression would add maintainability. The rule fires if all of the following conditions are met: +## The argument is a string literal or constant. +## The argument corresponds to a string-typed parameter of the method or the constructor that's being invoked (that is, there is no conversion involved at the call site). +## Either: +## The declared name of the parameter is paramName and the constant value of the string literal matches the name of a parameter of the method, lambda, or local function within which the method or constructor is being invoked. +## The declared name of the parameter is propertyName and the constant value of the string literal matches the name of a property of the type within which the method or constructor is being invoked. +## Rule CA1507 improves code maintainability in cases where the parameter may be renamed in the future, but the string literal is mistakenly not renamed. By using nameof, the symbol will be renamed when the parameter is renamed through a refactoring operation. In addition, any spelling mistakes in the name of the parameter are caught by the compiler. dotnet_diagnostic.CA1507.severity = suggestion -dotnet_diagnostic.CA1508.severity = warning -# dotnet_diagnostic.CA1509.severity = none -dotnet_diagnostic.CA1700.severity = none + +## Avoid dead conditional code (CA1508) +## Methods can have conditional code, such as if statements, binary expressions (==, !=, <, >), null checks, etc. For example, consider the following code: +## public void M(int i, int j) +## { +## if (i != 0) +## { +## return; +## } +## +## if (j != 0) +## { +## return; +## } +## +## // Below condition will always evaluate to 'false' as 'i' and 'j' are both '0' here. +## if (i != j) +## { +## // Code in this 'if' branch is dead code. +## // It can either be removed or refactored. +## ... +## } +## } +## C# and VB compilers perform analysis of conditional checks involving compile-time constant values that always evaluate to true or false. This analyzer performs data flow analysis of non-constant variables to determine redundant conditional checks involving non-constant values. In the preceding code, the analyzer determines that i and j are both 0 for all code paths that reach i != j check. Hence, this check will always evaluate to false at run time. The code inside the if statement is dead code and can be removed or refactored. Similarly, the analyzer tracks nullness of variables and reports redundant null checks. +## [!NOTE] +## This analyzer performs an expensive dataflow analysis of non-constant values. This can increase the overall compile time on certain code bases. +dotnet_diagnostic.CA1508.severity = suggestion + +## Invalid entry in code metrics configuration file (CA1509) +## The analysis rules for code metrics allow you to supply an additional file in your project named CodeMetricsConfig.txt. This file contains entries to configure code-metric thresholds for analysis. The following rules are configurable in this file: +## CA1501: Avoid excessive inheritance +## CA1502: Avoid excessive complexity +## CA1505: Avoid unmaintainable code +## CA1506: Avoid excessive class coupling +## This configuration file expects each entry to be in following format: +## 'RuleId'(Optional 'SymbolKind'): 'Threshold' +## Valid values for RuleId are CA1501, CA1502, CA1505, and CA1506. +## Valid values for the optional SymbolKind are Assembly, Namespace, Type, Method, Field, Event, and Property. +## Valid values for Threshold are non-negative integers. +## Lines starting with '#' are treated as comment lines. +## For example, the following is a valid configuration file: +## # Comment text +## +## CA1501: 1 +## +## CA1502(Type): 4 +## CA1502(Method): 2 +## An invalid entry in this configuration file is flagged with the CA1509 diagnostic. +dotnet_diagnostic.CA1509.severity = none + +## Do not name enum values 'Reserved' (CA1700) +## This rule assumes that an enumeration member that has a name that contains "reserved" is not currently used but is a placeholder to be renamed or removed in a future version. Renaming or removing a member is a breaking change. You should not expect users to ignore a member just because its name contains "reserved", nor can you rely on users to read or abide by documentation. Furthermore, because reserved members appear in object browsers and smart integrated development environments, they can cause confusion about which members are actually being used. +## Instead of using a reserved member, add a new member to the enumeration in the future version. In most cases the addition of the new member is not a breaking change, as long as the addition does not cause the values of the original members to change. +## In a limited number of cases the addition of a member is a breaking change even when the original members retain their original values. Primarily, the new member cannot be returned from existing code paths without breaking callers that use a switch (Select in Visual Basic) statement on the return value that encompasses the whole member list and that throw an exception in the default case. A secondary concern is that client code might not handle the change in behavior from reflection methods such as xref:System.Enum.IsDefined%2A?displayProperty=fullName. Accordingly, if the new member has to be returned from existing methods or a known application incompatibility occurs because of poor reflection usage, the only nonbreaking solution is to: +## Add a new enumeration that contains the original and new members. +## Mark the original enumeration with the xref:System.ObsoleteAttribute?displayProperty=fullName attribute. Follow the same procedure for any externally visible types or members that expose the original enumeration. +dotnet_diagnostic.CA1700.severity = warning + +## Identifiers should not contain underscores (CA1707) +## By convention, identifier names do not contain the underscore (_) character. The rule checks namespaces, types, members, and parameters. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the learning curve that is required for new software libraries, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. dotnet_diagnostic.CA1707.severity = warning + +## Identifiers should differ by more than case (CA1708) +## Identifiers for namespaces, types, members, and parameters cannot differ only by case because languages that target the common language runtime are not required to be case-sensitive. For example, Visual Basic is a widely used case-insensitive language. dotnet_diagnostic.CA1708.severity = none -dotnet_diagnostic.CA1710.severity = none -dotnet_diagnostic.CA1711.severity = none -dotnet_diagnostic.CA1712.severity = none -dotnet_diagnostic.CA1713.severity = none -dotnet_diagnostic.CA1714.severity = suggestion -dotnet_diagnostic.CA1715.severity = warning -dotnet_diagnostic.CA1716.severity = warning -dotnet_diagnostic.CA1717.severity = none -dotnet_diagnostic.CA1720.severity = warning -dotnet_diagnostic.CA1721.severity = warning + +## Identifiers should have correct suffix (CA1710) +## By convention, the names of types that extend certain base types or that implement certain interfaces, or types derived from these types, have a suffix that is associated with the base type or interface. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the learning curve that is required for new software libraries, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +## The following table lists the base types and interfaces that have associated suffixes. +## Base type/Interface Suffix xref:System.Attribute?displayProperty=fullName Attribute xref:System.EventArgs?displayProperty=fullName EventArgs xref:System.Exception?displayProperty=fullName Exception xref:System.Collections.ICollection?displayProperty=fullName Collection xref:System.Collections.IDictionary?displayProperty=fullName Dictionary xref:System.Collections.IEnumerable?displayProperty=fullName Collection xref:System.Collections.Generic.IReadOnlyDictionary%602?displayProperty=fullName Dictionary xref:System.Collections.Queue?displayProperty=fullName Collection or Queue xref:System.Collections.Stack?displayProperty=fullName Collection or Stack xref:System.Collections.Generic.ICollection%601?displayProperty=fullName Collection xref:System.Collections.Generic.IDictionary%602?displayProperty=fullName Dictionary xref:System.Data.DataSet?displayProperty=fullName DataSet xref:System.Data.DataTable?displayProperty=fullName Collection or DataTable xref:System.IO.Stream?displayProperty=fullName Stream xref:System.Security.IPermission?displayProperty=fullName Permission xref:System.Security.Policy.IMembershipCondition?displayProperty=fullName Condition An event-handler delegate. EventHandler +## Types that implement xref:System.Collections.ICollection and are a generalized type of data structure, such as a dictionary, stack, or queue, are allowed names that provide meaningful information about the intended usage of the type. +## Types that implement xref:System.Collections.ICollection and are a collection of specific items have names that end with the word 'Collection'. For example, a collection of xref:System.Collections.Queue objects would have the name 'QueueCollection'. The 'Collection' suffix signifies that the members of the collection can be enumerated by using the foreach (For Each in Visual Basic) statement. +## Types that implement xref:System.Collections.IDictionary or xref:System.Collections.Generic.IReadOnlyDictionary%602 have names that end with the word 'Dictionary' even if the type also implements xref:System.Collections.IEnumerable or xref:System.Collections.ICollection. The 'Collection' and 'Dictionary' suffix naming conventions enable users to distinguish between the following two enumeration patterns. +## Types with the 'Collection' suffix follow this enumeration pattern. +## foreach(SomeType x in SomeCollection) { } +## Types with the 'Dictionary' suffix follow this enumeration pattern. +## foreach(SomeType x in SomeDictionary.Values) { } +## A xref:System.Data.DataSet object consists of a collection of xref:System.Data.DataTable objects, which consist of collections of xref:System.Data.DataColumn?displayProperty=fullName and xref:System.Data.DataRow?displayProperty=fullName objects, among others. These collections implement xref:System.Collections.ICollection through the base xref:System.Data.InternalDataCollectionBase?displayProperty=fullName class. +dotnet_diagnostic.CA1710.severity = warning + +## Identifiers should not have incorrect suffix (CA1711) +## By convention, only the names of types that extend certain base types or that implement certain interfaces, or types derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes. +## The following table lists the reserved suffixes and the base types and interfaces with which they are associated. +## Suffix Base type/Interface Attribute xref:System.Attribute?displayProperty=fullName Collection xref:System.Collections.ICollection?displayProperty=fullNamexref:System.Collections.IEnumerable?displayProperty=fullNamexref:System.Collections.Queue?displayProperty=fullNamexref:System.Collections.Stack?displayProperty=fullNamexref:System.Collections.Generic.ICollection%601?displayProperty=fullNamexref:System.Data.DataSet?displayProperty=fullNamexref:System.Data.DataTable?displayProperty=fullName Dictionary xref:System.Collections.IDictionary?displayProperty=fullNamexref:System.Collections.Generic.IDictionary%602?displayProperty=fullName EventArgs xref:System.EventArgs?displayProperty=fullName EventHandler An event-handler delegate Exception xref:System.Exception?displayProperty=fullName Permission xref:System.Security.IPermission?displayProperty=fullName Queue xref:System.Collections.Queue?displayProperty=fullName Stack xref:System.Collections.Stack?displayProperty=fullName Stream xref:System.IO.Stream?displayProperty=fullName +## In addition, the following suffixes should not be used: +## Delegate +## Enum +## Impl (use Core instead) +## Ex or similar suffix to distinguish it from an earlier version of the same type +## Flag or Flags for enum types +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the learning curve that is required for new software libraries, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. For more information, see Naming guidelines: Classes, Structs, and Interfaces. +dotnet_diagnostic.CA1711.severity = warning + +## Do not prefix enum values with type name (CA1712) +## Names of enumeration members are not prefixed with the type name because type information is expected to be provided by development tools. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the time that is required for to learn a new software library, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +dotnet_diagnostic.CA1712.severity = warning + +## Events should not have before or after prefix (CA1713) +## Event names should describe the action that raises the event. To name related events that are raised in a specific sequence, use the present or past tense to indicate the relative position in the sequence of actions. For example, when naming a pair of events that is raised when closing a resource, you might name it 'Closing' and 'Closed', instead of 'BeforeClose' and 'AfterClose'. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the learning curve that is required for new software libraries, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +dotnet_diagnostic.CA1713.severity = warning + +## Flags enums should have plural names (CA1714) +## Types that are marked with xref:System.FlagsAttribute have names that are plural because the attribute indicates that more than one value can be specified. For example, an enumeration that defines the days of the week might be intended for use in an application where you can specify multiple days. This enumeration should have the xref:System.FlagsAttribute and could be called 'Days'. A similar enumeration that allows only a single day to be specified would not have the attribute, and could be called 'Day'. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the learning curve that is required for new software libraries, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +dotnet_diagnostic.CA1714.severity = warning + +## Identifiers should have correct prefix (CA1715) +## By convention, the names of certain programming elements start with a specific prefix. +## Interface names should start with an uppercase 'I' followed by another uppercase letter. This rule reports violations for interface names such as 'MyInterface' and 'IsolatedInterface'. +## Generic type parameter names should start with an uppercase 'T' and optionally may be followed by another uppercase letter. This rule reports violations for generic type parameter names such as 'V' and 'Type'. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the learning curve that is required for new software libraries, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +dotnet_diagnostic.CA1715.severity = suggestion + +## Identifiers should not match keywords (CA1716) +## Identifiers for namespaces, types, and virtual and interface members should not match keywords that are defined by languages that target the common language runtime. Depending on the language that is used and the keyword, compiler errors and ambiguities can make the library difficult to use. +## This rule checks against keywords in the following languages: +## Visual Basic +## C# +## C++/CLI +## Case-insensitive comparison is used for Visual Basic keywords, and case-sensitive comparison is used for the other languages. +dotnet_diagnostic.CA1716.severity = suggestion + +## Only FlagsAttribute enums should have plural names (CA1717) +## Naming conventions dictate that a plural name for an enumeration indicates that more than one value of the enumeration can be specified simultaneously. The xref:System.FlagsAttribute tells compilers that the enumeration should be treated as a bit field that enables bitwise operations on the enumeration. +## If only one value of an enumeration can be specified at a time, the name of the enumeration should be a singular word. For example, an enumeration that defines the days of the week might be intended for use in an application where you can specify multiple days. This enumeration should have the xref:System.FlagsAttribute and could be called 'Days'. A similar enumeration that allows only a single day to be specified would not have the attribute, and could be called 'Day'. +## Naming conventions provide a common look for libraries that target the common language runtime. This reduces the time that is required to learn a new software library, and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +dotnet_diagnostic.CA1717.severity = suggestion + +## Identifiers should not contain type names (CA1720) +## Names of parameters and members are better used to communicate their meaning than to describe their type, which is expected to be provided by development tools. For names of members, if a data type name must be used, use a language-independent name instead of a language-specific one. For example, instead of the C# type name int, use the language-independent data type name, Int32. +## Each discrete token in the name of the parameter or member is checked against the following language-specific data type names in a case-insensitive manner: +## Bool +## WChar +## Int8 +## UInt8 +## Short +## UShort +## Int +## UInt +## Integer +## UInteger +## Long +## ULong +## Unsigned +## Signed +## Float +## Float32 +## Float64 +## In addition, the names of a parameter are also checked against the following language-independent data type names in a case-insensitive manner: +## Object +## Boolean +## Char +## String +## SByte +## Byte +## UByte +## Int16 +## UInt16 +## Int32 +## UInt32 +## Int64 +## UInt64 +## IntPtr +## Ptr +## Pointer +## UInptr +## UPtr +## UPointer +## Single +## Double +## Decimal +## Guid +dotnet_diagnostic.CA1720.severity = suggestion + +## Property names should not match get methods (CA1721) +## "Get" methods and properties should have names that clearly distinguish their function. +## Naming conventions provide a common look for libraries that target the common language runtime. This consistency reduces the time that's required to learn a new software library and increases customer confidence that the library was developed by someone who has expertise in developing managed code. +dotnet_diagnostic.CA1721.severity = suggestion + +## Type names should not match namespaces (CA1724) +## User-created type names should not match the names of referenced namespaces that have externally visible types. Violating this rule can reduce the usability of your library. dotnet_diagnostic.CA1724.severity = warning + +## Parameter names should match base declaration (CA1725) +## Consistent naming of parameters in an override hierarchy increases the usability of the method overrides. A parameter name in a derived method that differs from the name in the base declaration can cause confusion about whether the method is an override of the base method or a new overload of the method. dotnet_diagnostic.CA1725.severity = warning -dotnet_diagnostic.CA1727.severity = none + +## Use PascalCase for named placeholders (CA1727) +## A named placeholder used with xref:Microsoft.Extensions.Logging.ILogger should be PascalCase, a naming convention where the first letter of each compound word in a name is capitalized. This naming convention is recommended for structured logging, where each named placeholder is used as a property name in the structured data. +dotnet_diagnostic.CA1727.severity = suggestion + +## Review unused parameters (CA1801) +## Review parameters in non-virtual methods that are not used in the method body to make sure no incorrectness exists around failure to access them. Unused parameters incur maintenance and performance costs. +## Sometimes, a violation of this rule can point to an implementation bug in the method. For example, the parameter should have been used in the method body. Suppress warnings of this rule if the parameter must exist because of backward compatibility. dotnet_diagnostic.CA1801.severity = warning + +## Use Literals Where Appropriate (CA1802) +## The value of a static readonly field is computed at run time when the static constructor for the declaring type is called. If the static readonly field is initialized when it is declared and a static constructor is not declared explicitly, the compiler emits a static constructor to initialize the field. +## The value of a const field is computed at compile time and stored in the metadata, which improves run-time performance when it is compared to a static readonly field. +## Because the value assigned to the targeted field is computable at compile time, change the declaration to a const field so that the value is computed at compile time instead of at run time. dotnet_diagnostic.CA1802.severity = warning -dotnet_diagnostic.CA1805.severity = none -dotnet_diagnostic.CA1806.severity = none + +## Do not initialize unnecessarily (CA1805) +## The .NET runtime initializes all fields of reference types to their default values before running the constructor. In most cases, explicitly initializing a field to its default value in a constructor is redundant, adding maintenance costs and potentially degrading performance (such as with increased assembly size), and the explicit initialization can be removed. +dotnet_diagnostic.CA1805.severity = warning + +## Do not ignore method results (CA1806) +## Unnecessary object creation and the associated garbage collection of the unused object degrade performance. +## Strings are immutable and methods such as xref:System.String.ToUpper%2A?displayProperty=nameWithType return a new instance of a string instead of modifying the instance of the string in the calling method. +## Ignoring HRESULT or an error code can lead to low-resource conditions or unexpected behavior in error conditions. +## LINQ methods are known to not have side effects, and the result should not be ignored. +dotnet_diagnostic.CA1806.severity = suggestion + +## Initialize reference type static fields inline (CA1810) +## When a type declares an explicit static constructor, the just-in-time (JIT) compiler adds a check to each static method and instance constructor of the type to make sure that the static constructor was previously called. Static initialization is triggered when any static member is accessed or when an instance of the type is created. However, static initialization is not triggered if you declare a variable of the type but do not use it, which can be important if the initialization changes global state. +## When all static data is initialized inline and an explicit static constructor is not declared, Microsoft intermediate language (MSIL) compilers add the beforefieldinit flag and an implicit static constructor, which initializes the static data, to the MSIL type definition. When the JIT compiler encounters the beforefieldinit flag, most of the time the static constructor checks are not added. Static initialization is guaranteed to occur at some time before any static fields are accessed but not before a static method or instance constructor is invoked. Note that static initialization can occur at any time after a variable of the type is declared. +## Static constructor checks can decrease performance. Often a static constructor is used only to initialize static fields, in which case you must only make sure that static initialization occurs before the first access of a static field. The beforefieldinit behavior is appropriate for these and most other types. It is only inappropriate when static initialization affects global state and one of the following is true: +## The effect on global state is expensive and is not required if the type is not used. +## The global state effects can be accessed without accessing any static fields of the type. dotnet_diagnostic.CA1810.severity = none + +## Avoid uninstantiated internal classes (CA1812) +## This rule tries to locate a call to one of the constructors of the type and reports a violation if no call is found. +## The following types are not examined by this rule: +## Value types +## Abstract types +## Enumerations +## Delegates +## Compiler-emitted array types +## Types that can't be instantiated and that only define static methods. +## If you apply xref:System.Runtime.CompilerServices.InternalsVisibleToAttribute?displayProperty=fullName to the assembly that's being analyzed, this rule doesn't flag types that are marked as internal (Friend in Visual Basic) by default, because a field may be used by a friend assembly. To analyze the assembly anyway, see Configure code to analyze. dotnet_diagnostic.CA1812.severity = none -# dotnet_diagnostic.CA1812.severity = warning -dotnet_diagnostic.CA1813.severity = warning -dotnet_diagnostic.CA1814.severity = warning -dotnet_diagnostic.CA1815.severity = suggestion + +## Avoid unsealed attributes (CA1813) +## .NET provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. For example, xref:System.Attribute.GetCustomAttribute%2A?displayProperty=fullName searches for the specified attribute type or any attribute type that extends the specified attribute type. Sealing the attribute eliminates the search through the inheritance hierarchy, and can improve performance. +dotnet_diagnostic.CA1813.severity = silent + +## Prefer jagged arrays over multidimensional (CA1814) +## In a multidimensional array, each element in each dimension has the same, fixed size as the other elements in that dimension. In a jagged array, which is an array of arrays, each inner array can be of a different size. By only using the space that's needed for a given array, no space is wasted. This rule, CA1814, recommends switching to a jagged array to conserve memory. +dotnet_diagnostic.CA1814.severity = silent + +## Override equals and operator equals on value types (CA1815) +## For non-blittable value types, the inherited implementation of xref:System.Object.Equals%2A uses the xref:System.Reflection library to compare the contents of all fields. Reflection is computationally expensive, and comparing every field for equality might be unnecessary. If you expect users to compare or sort instances, or use them as hash table keys, your value type should implement xref:System.Object.Equals%2A. If your programming language supports operator overloading, you should also provide an implementation of the equality and inequality operators. +dotnet_diagnostic.CA1815.severity = warning + +## Call GC.SuppressFinalize correctly (CA1816) +## The xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType method lets users release resources at any time before the object becoming available for garbage collection. If the xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType method is called, it frees resources of the object. This makes finalization unnecessary. xref:System.IDisposable.Dispose%2A?displayProperty=nameWithType should call xref:System.GC.SuppressFinalize%2A?displayProperty=nameWithType so the garbage collector doesn't call the finalizer of the object. +## To prevent derived types with finalizers from having to reimplement xref:System.IDisposable and to call it, unsealed types without finalizers should still call xref:System.GC.SuppressFinalize%2A?displayProperty=nameWithType. dotnet_diagnostic.CA1816.severity = none -dotnet_diagnostic.CA1819.severity = none -dotnet_diagnostic.CA1820.severity = warning + +## Properties should not return arrays (CA1819) +## Arrays returned by properties are not write-protected, even if the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users won't understand the adverse performance implications of calling such a property. Specifically, they might use the property as an indexed property. +dotnet_diagnostic.CA1819.severity = warning + +## Test for empty strings using string length (CA1820) +## Comparing strings using the xref:System.String.Length%2A?displayProperty=nameWithType property or the xref:System.String.IsNullOrEmpty%2A?displayProperty=nameWithType method is faster than using xref:System.Object.Equals%2A. This is because xref:System.Object.Equals%2A executes significantly more MSIL instructions than either xref:System.String.IsNullOrEmpty%2A or the number of instructions executed to retrieve the xref:System.String.Length%2A property value and compare it to zero. +## For null strings, xref:System.Object.Equals%2A and .Length == 0 behave differently. If you try to get the value of the xref:System.String.Length%2A property on a null string, the common language runtime throws a xref:System.NullReferenceException?displayProperty=fullName. If you perform a comparison between a null string and the empty string, the common language runtime does not throw an exception and returns false. Testing for null does not significantly affect the relative performance of these two approaches. When targeting .NET Framework 2.0 or later, use the xref:System.String.IsNullOrEmpty%2A method. Otherwise, use the xref:System.String.Length%2A == 0 comparison whenever possible. +dotnet_diagnostic.CA1820.severity = silent + +## Remove empty finalizers (CA1821) +## Whenever you can, avoid finalizers because of the additional performance overhead that's involved in tracking object lifetime. The garbage collector runs the finalizer before it collects the object. This means that at least two collections are required to collect the object. An empty finalizer incurs this added overhead without any benefit. dotnet_diagnostic.CA1821.severity = warning + +## Mark members as static (CA1822) +## Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at run time for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue. dotnet_diagnostic.CA1822.severity = none + +## Avoid unused private fields (CA1823) +## Private fields were detected that do not appear to be accessed in the assembly. dotnet_diagnostic.CA1823.severity = warning + +## Mark assemblies with NeutralResourcesLanguageAttribute (CA1824) +## The xref:System.Resources.NeutralResourcesLanguageAttribute attribute informs the resource manager of an app's default culture. If the default culture's resources are embedded in the app's main assembly, and xref:System.Resources.ResourceManager has to retrieve resources that belong to the same culture as the default culture, the xref:System.Resources.ResourceManager automatically uses the resources located in the main assembly instead of searching for a satellite assembly. This bypasses the usual assembly probe, improves lookup performance for the first resource you load, and can reduce your working set. +## [!TIP] +## See Package and deploy resources for the process that xref:System.Resources.ResourceManager uses to probe for resource files. dotnet_diagnostic.CA1824.severity = none + +## Avoid zero-length array allocations (CA1825) +## Initializing a zero-length array leads to an unnecessary memory allocation. Instead, use the statically allocated empty array instance by calling the xref:System.Array.Empty%2A?displayProperty=nameWithType method. The memory allocation is shared across all invocations of this method. dotnet_diagnostic.CA1825.severity = warning -dotnet_diagnostic.CA1826.severity = none + +## Use property instead of Linq Enumerable method (CA1826) +## This rule flags the xref:System.Linq.Enumerable LINQ method calls on collections of types that have equivalent but more efficient properties to fetch the same data. +## This rule analyzes collection types that implement xref:System.Collections.Generic.IReadOnlyList%601 but not xref:System.Collections.Generic.IList%601. +## This rule flags calls to the following methods on these collection types: +## xref:System.Linq.Enumerable.Count%2A?displayProperty=fullName +## xref:System.Linq.Enumerable.First%2A?displayProperty=fullName +## xref:System.Linq.Enumerable.FirstOrDefault%2A?displayProperty=fullName +## xref:System.Linq.Enumerable.Last%2A?displayProperty=fullName +## xref:System.Linq.Enumerable.LastOrDefault%2A?displayProperty=fullName +## The analyzed collection types and methods may be extended in the future to cover more cases. +dotnet_diagnostic.CA1826.severity = suggestion + +## Do not use Count()/LongCount() when Any() can be used (CA1827) +## This rule flags Count() and LongCount() LINQ method calls that are used to check if the collection has at least one element. These methods enumerate the entire collection to compute the count. The same check is faster with the Any() method as it avoids enumerating the collection. +## [!NOTE] +## This rule is similar to CA1860: Avoid using 'Enumerable.Any()' extension method. However that rule suggests using the Count property, while this rule applies to the Linq Count() extension method. dotnet_diagnostic.CA1827.severity = warning + +## Do not use CountAsync/LongCountAsync when AnyAsync can be used (CA1828) +## This rule flags the xref:Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.CountAsync%2A and xref:Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.LongCountAsync%2A LINQ method calls used to check if the collection has at least one element. These method calls require enumerating the entire collection to compute the count. The same check is faster with the xref:Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.AnyAsync%2A method as it avoids enumerating the collection. dotnet_diagnostic.CA1828.severity = warning + +## Use Length/Count property instead of Enumerable.Count method (CA1829) +## This rule flags the xref:System.Linq.Enumerable.Count%2A LINQ method calls on collections of types that have equivalent, but more efficient Length or Count property to fetch the same data. Length or Count property does not enumerate the collection, hence is more efficient. +## This rule flags xref:System.Linq.Enumerable.Count%2A calls on the following collection types with Length property: +## xref:System.Array?displayProperty=fullName +## xref:System.Collections.Immutable.ImmutableArray%601?displayProperty=fullName +## This rule flags xref:System.Linq.Enumerable.Count%2A calls on the following collection types with the Count property: +## xref:System.Collections.ICollection?displayProperty=fullName +## xref:System.Collections.Generic.ICollection%601?displayProperty=fullName +## xref:System.Collections.Generic.IReadOnlyCollection%601?displayProperty=fullName +## The analyzed collection types may be extended in the future to cover more cases. dotnet_diagnostic.CA1829.severity = warning + +## Prefer strongly-typed Append and Insert method overloads on StringBuilder (CA1830) +## xref:System.Text.StringBuilder.Append%2A and xref:System.Text.StringBuilder.Insert%2A provide overloads for multiple types beyond xref:System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload. dotnet_diagnostic.CA1830.severity = suggestion -dotnet_diagnostic.CA1831.severity = suggestion -dotnet_diagnostic.CA1832.severity = suggestion -dotnet_diagnostic.CA1833.severity = suggestion -dotnet_diagnostic.CA1834.severity = suggestion -dotnet_diagnostic.CA1835.severity = suggestion + +## Use AsSpan instead of Range-based indexers for string when appropriate (CA1831) +## This rule fires when you use a range-indexer on a string and assign it to a span type. The range indexer on a xref:System.Span%601 is a non-copying xref:System.Span%601.Slice%2A?#System_Span_1_Slice_System_Int32_System_Int32_ operation, but for the range indexer on a string, the method xref:System.String.Substring%2A?#System_String_Substring_System_Int32_System_Int32_ will be used instead of xref:System.Span%601.Slice%2A?#System_Span_1_Slice_System_Int32_System_Int32_. This produces a copy of the requested portion of the string. This copy is usually unnecessary when it's implicitly used as a xref:System.ReadOnlySpan%601 or xref:System.ReadOnlyMemory%601 value. If a copy isn't intended, use the xref:System.MemoryExtensions.AsSpan%2A?#System_MemoryExtensions_AsSpan_System_String_AsSpan method to avoid the unnecessary copy. If the copy is intended, either assign it to a local variable first or add an explicit cast. The analyzer only reports when an implicit cast is used on the result of the range indexer operation. +dotnet_diagnostic.CA1831.severity = warning + +## Use AsSpan or AsMemory instead of Range-based indexers for getting ReadOnlySpan or ReadOnlyMemory portion of an array (CA1832) +## The range indexer on a xref:System.Span%601 is a non-copying xref:System.Span%601.Slice%2A?#System_Span_1_Slice_System_Int32_System_Int32_ operation. But for the range indexer on an array, the method xref:System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray%2A will be used instead of xref:System.Span%601.Slice%2A?#System_Span_1_Slice_System_Int32_System_Int32_, which produces a copy of the requested portion of the array. This copy is usually unnecessary when it's implicitly used as a xref:System.ReadOnlySpan%601 or xref:System.ReadOnlyMemory%601 value. If a copy isn't intended, use the xref:System.MemoryExtensions.AsSpan%2A?#System_MemoryExtensions_AsSpan__1___0___ or xref:System.MemoryExtensions.AsMemory%2A?#System_MemoryExtensions_AsMemory__1___0___ method to avoid the unnecessary copy. If the copy is intended, either assign it to a local variable first or add an explicit cast. +## The analyzer only reports when an implicit cast is used on the result of the range indexer operation. +dotnet_diagnostic.CA1832.severity = warning + +## Use AsSpan or AsMemory instead of Range-based indexers for getting Span or Memory portion of an array (CA1833) +## The range indexer on a xref:System.Span%601 is a non-copying xref:System.Span%601.Slice%2A?#System_Span_1_Slice_System_Int32_System_Int32_ operation. But for the range indexer on an array, the method xref:System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray%2A will be used instead of xref:System.Span%601.Slice%2A?#System_Span_1_Slice_System_Int32_System_Int32_, which produces a copy of the requested portion of the array. This copy is usually unnecessary when it's implicitly used as a xref:System.Span%601 or xref:System.Memory%601 value. If a copy isn't intended, use the xref:System.MemoryExtensions.AsSpan%2A?#System_MemoryExtensions_AsSpan__1___0___ or xref:System.MemoryExtensions.AsMemory%2A?#System_MemoryExtensions_AsMemory__1___0___ method to avoid the unnecessary copy. If the copy is intended, either assign it to a local variable first or add an explicit cast. The analyzer only reports when an implicit cast is used on the result of the range indexer operation. +dotnet_diagnostic.CA1833.severity = warning + +## Use StringBuilder.Append(char) for single character strings (CA1834) +## When calling StringBuilder.Append with a unit length string, consider using a const char rather than a unit length const string to improve performance. +dotnet_diagnostic.CA1834.severity = warning + +## Prefer the memory-based overloads of ReadAsync/WriteAsync methods in stream-based classes (CA1835) +## The memory-based method overloads have a more efficient memory usage than the byte array-based ones. +## The rule works on ReadAsync and WriteAsync invocations of any class that inherits from xref:System.IO.Stream. +## The rule only works when the method is preceded by the await keyword. +## Detected method Suggested method xref:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32,System.Threading.CancellationToken) xref:System.IO.Stream.ReadAsync(System.Memory{System.Byte},System.Threading.CancellationToken) xref:System.IO.Stream.ReadAsync(System.Byte[],System.Int32,System.Int32) xref:System.IO.Stream.ReadAsync(System.Memory{System.Byte},System.Threading.CancellationToken) with CancellationToken set to default in C#, or Nothing in Visual Basic. xref:System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32,System.Threading.CancellationToken) xref:System.IO.Stream.WriteAsync(System.ReadOnlyMemory{System.Byte},System.Threading.CancellationToken) xref:System.IO.Stream.WriteAsync(System.Byte[],System.Int32,System.Int32) xref:System.IO.Stream.WriteAsync(System.ReadOnlyMemory{System.Byte},System.Threading.CancellationToken) with CancellationToken set to default in C#, or Nothing in Visual Basic. +## [!IMPORTANT] +## Make sure to pass the offset and count integer arguments to the created Memory or ReadOnlyMemory instances. +## [!NOTE] +## Rule CA1835 is available in all .NET versions where the memory-based overloads are available: +## .NET Standard 2.1 and above. +## .NET Core 2.1 and above. +dotnet_diagnostic.CA1835.severity = warning + +## Prefer IsEmpty over Count when available (CA1836) +## This rule flags the calls to the Count and Length properties or xref:System.Linq.Enumerable.Count%60%601%28System.Collections.Generic.IEnumerable%7B%60%600%7D%29 and xref:System.Linq.Enumerable.LongCount%60%601%28System.Collections.Generic.IEnumerable%7B%60%600%7D%29 LINQ methods when they are used to determine if the object contains any items and the object has a more efficient IsEmpty property. +## The analysis of this rule originally overlapped with similar rules CA1827, CA1828, and CA1829; the analyzers of such rules were merged along with the one for CA1836 to report the best diagnosis in case of overlap. dotnet_diagnostic.CA1836.severity = warning + +## Use Environment.ProcessId instead of Process.GetCurrentProcess().Id (CA1837) +## System.Diagnostics.Process.GetCurrentProcess().Id is expensive: +## It allocates a xref:System.Diagnostics.Process instance, usually just to get the Id. +## The xref:System.Diagnostics.Process instance needs to be disposed, which has a performance impact. +## It's easy to forget to call xref:System.Diagnostics.Process.Dispose on the xref:System.Diagnostics.Process instance. +## If nothing else besides Id uses the Process instance, then the linked size grows unnecessarily by increasing the graph of types referenced. +## It is somewhat difficult to discover or find this API. +## System.Environment.ProcessId avoids all the above. +## [!NOTE] +## Rule CA1837 is available starting on .NET 5.0. dotnet_diagnostic.CA1837.severity = warning -dotnet_diagnostic.CA1838.severity = warning -dotnet_diagnostic.CA1841.severity = none -dotnet_diagnostic.CA1842.severity = none -dotnet_diagnostic.CA1843.severity = none -dotnet_diagnostic.CA1844.severity = warning -dotnet_diagnostic.CA1845.severity = suggestion + +## Avoid StringBuilder parameters for P/Invokes (CA1838) +## Marshalling of StringBuilder always creates a native buffer copy, resulting in multiple allocations for one P/Invoke call. To marshal a StringBuilder as a P/Invoke parameter, the runtime will: +## Allocate a native buffer. +## If it is an In parameter, copy the contents of the StringBuilder to the native buffer. +## If it is an Out parameter, copy the native buffer into a newly allocated managed array. +## By default, StringBuilder is In and Out. +## For more information about marshalling strings, see Default marshalling for strings. +## This rule is disabled by default, because it can require case-by-case analysis of whether the violation is of interest and potentially non-trivial refactoring to address the violation. Users can explicitly enable this rule by configuring its severity. +dotnet_diagnostic.CA1838.severity = none + +## Use Environment.ProcessPath instead of Process.GetCurrentProcess().MainModule.FileName (CA1839) +## System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName is expensive: +## It allocates a xref:System.Diagnostics.Process and xref:System.Diagnostics.ProcessModule instance, usually just to get the FileName. +## The xref:System.Diagnostics.Process instance needs to be disposed, which has a performance impact. +## It's easy to forget to call xref:System.Diagnostics.Process.Dispose on the xref:System.Diagnostics.Process instance. +## If nothing else besides FileName uses the Process instance, then the linked size grows unnecessarily by increasing the graph of types referenced. +## It is somewhat difficult to discover or find this API. +## System.Environment.ProcessPath avoids all of these downsides and produces the same information. +## [!NOTE] +## xref:System.Environment.ProcessPath?displayProperty=fullName is available starting in .NET 6. +dotnet_diagnostic.CA1839.severity = warning + +## Use Environment.CurrentManagedThreadId instead of Thread.CurrentThread.ManagedThreadId (CA1840) +## xref:System.Environment.CurrentManagedThreadId?displayProperty=fullName is a compact and efficient replacement of the Thread.CurrentThread.ManagedThreadId pattern. +dotnet_diagnostic.CA1840.severity = warning + +## Prefer Dictionary Contains methods (CA1841) +## Calling Contains on the Keys or Values collection can often be more expensive than calling ContainsKey or ContainsValue on the dictionary itself: +## Many dictionary implementations lazily instantiate the key and value collections, which means that accessing the Keys or Values collection may result in extra allocations. +## You may end up calling an extension method on xref:System.Collections.Generic.IEnumerable%601 if the keys or values collection uses explicit interface implementation to hide methods on xref:System.Collections.Generic.ICollection%601. This can lead to reduced performance, especially when accessing the key collection. Most dictionary implementations are able to provide a fast O(1) containment check for keys, while the Contains extension method on xref:System.Collections.Generic.IEnumerable%601 usually does a slow O(n) containment check. +dotnet_diagnostic.CA1841.severity = suggestion + +## Do not use 'WhenAll' with a single task (CA1842) +## Using WhenAll with a single task may result in performance loss. +dotnet_diagnostic.CA1842.severity = suggestion + +## Do not use 'WaitAll' with a single task (CA1843) +## Using WaitAll with a single task may result in performance loss. +dotnet_diagnostic.CA1843.severity = suggestion + +## Provide memory-based overrides of async methods when subclassing 'Stream' (CA1844) +## The memory-based ReadAsync and WriteAsync methods were added to improve performance, which they accomplish in multiple ways: +## They return ValueTask and ValueTask instead of Task and Task, respectively. +## They allow any type of buffer to be passed in without having to perform an extra copy to an array. +## In order to realize these performance benefits, types that derive from xref:System.IO.Stream must provide their own memory-based implementation. Otherwise, the default implementation will be forced to copy the memory into an array in order to call the array-based implementation, resulting in reduced performance. When the caller passes in a xref:System.Memory%601 or xref:System.ReadOnlyMemory%601 instance that's not backed by an array, performance is affected more. +dotnet_diagnostic.CA1844.severity = suggestion + +## Use span-based 'string.Concat' (CA1845) +## Calling Substring produces a copy of the extracted substring. By using AsSpan instead of Substring and calling the overload of string.Concat that accepts spans, you can eliminate the unnecessary string allocation. +dotnet_diagnostic.CA1845.severity = warning + +## Prefer AsSpan over Substring (CA1846) +## Substring allocates a new string object on the heap and performs a full copy of the extracted text. String manipulation is a performance bottleneck for many programs. Allocating many small, short-lived strings on a hot path can create enough collection pressure to impact performance. The O(n) copies created by Substring become relevant when the substrings get large. The xref:System.Span%601 and xref:System.ReadOnlySpan%601 types were created to solve these performance problems. +## Many APIs that accept strings also have overloads that accept a ReadOnlySpan argument. When such overloads are available, you can improve performance by calling AsSpan instead of Substring. dotnet_diagnostic.CA1846.severity = suggestion -dotnet_diagnostic.CA1847.severity = suggestion -dotnet_diagnostic.CA1848.severity = none -dotnet_diagnostic.CA1849.severity = suggestion + +## Use string.Contains(char) instead of string.Contains(string) with single characters (CA1847) +## When searching for a single character, using string.Contains(char) offers better performance than string.Contains(string). +dotnet_diagnostic.CA1847.severity = warning + +## Use the LoggerMessage delegates (CA1848) +## For high-performance logging scenarios, use the xref:Microsoft.Extensions.Logging.LoggerMessage pattern. +dotnet_diagnostic.CA1848.severity = suggestion + +## Call async methods when in an async method (CA1849) +## In a method which is already asynchronous, calls to other methods should be to their async versions, where they exist. +dotnet_diagnostic.CA1849.severity = warning + +## Prefer static HashData method over ComputeHash (CA1850) +## Static HashData methods were introduced in .NET 5 on the following types: +## xref:System.Security.Cryptography.MD5 +## xref:System.Security.Cryptography.SHA1 +## xref:System.Security.Cryptography.SHA256 +## xref:System.Security.Cryptography.SHA384 +## xref:System.Security.Cryptography.SHA512 +## These methods help simplify code in cases where you just want to hash some data. +## It's more efficient to use theses static HashData methods than to create and manage a HashAlgorithm instance to call ComputeHash. dotnet_diagnostic.CA1850.severity = suggestion + +## Possible multiple enumerations of IEnumerable collection (CA1851) +## A collection of type IEnumerable or IEnumerable has the ability to defer enumeration when it's generated. Many LINQ methods, such as Select, use deferred execution. Enumeration starts when the collection is passed into a LINQ enumeration method, like ElementAt, or used in a for each statement. The enumeration result is not calculated once and cached, like Lazy. +## If the enumeration operation itself is expensive, for example, a query into a database, multiple enumerations would hurt the performance of the program. +## If the enumeration operation has side effects, multiple enumerations might result in bugs. dotnet_diagnostic.CA1851.severity = warning -dotnet_diagnostic.CA1854.severity = suggestion -dotnet_diagnostic.CA2000.severity = suggestion -# dotnet_diagnostic.CA2000.severity = warning -dotnet_diagnostic.CA2002.severity = none + +## Seal internal types (CA1852) +## When a type isn't accessible outside its assembly and has no subtypes within its containing assembly, it can be safely sealed. Sealing types can improve performance. +## If you apply xref:System.Runtime.CompilerServices.InternalsVisibleToAttribute?displayProperty=fullName to the assembly that's being analyzed, this rule doesn't flag types that aren't marked as sealed by default, because a field may be used by a friend assembly. To analyze the assembly anyway, see Configure code to analyze. +dotnet_diagnostic.CA1852.severity = suggestion + +## Unnecessary call to 'Dictionary.ContainsKey(key)' (CA1853) +## There's no need to guard Dictionary.Remove(key) with Dictionary.ContainsKey(key). xref:System.Collections.Generic.Dictionary%602.Remove(%600)?displayProperty=nameWithType already checks whether the key exists and doesn't throw if it doesn't exist. +dotnet_diagnostic.CA1853.severity = suggestion + +## Prefer the IDictionary.TryGetValue(TKey, out TValue) method (CA1854) +## When an element of an IDictionary is accessed, the indexer implementation checks for a null value by calling the IDictionary.ContainsKey method. If you also call IDictionary.ContainsKey in an if clause to guard a value lookup, two lookups are performed when only one is needed. +dotnet_diagnostic.CA1854.severity = warning + +## Use Span.Clear() instead of Span.Fill() (CA1855) +## It's more efficient to call xref:System.Span%601.Clear?displayProperty=nameWithType than to call xref:System.Span%601.Fill(%600)?displayProperty=nameWithType to fill the elements of the span with a default value. +dotnet_diagnostic.CA1855.severity = suggestion + +## Use StartsWith instead of IndexOf (CA1858) +## It's more efficient and clearer to call xref:System.String.StartsWith%2A?displayProperty=nameWithType than to call xref:System.String.IndexOf%2A?displayProperty=nameWithType and compare the result with zero to determine whether a string starts with a given prefix. +## IndexOf searches the entire string, while StartsWith only compares at the beginning of the string. +dotnet_diagnostic.CA1858.severity = suggestion + +## Use concrete types when possible for improved performance (CA1859) +## This rule recommends upgrading the type of specific local variables, fields, properties, method parameters, and method return types from interface or abstract +## types to concrete types when possible. Using concrete types leads to higher quality generated code by minimizing virtual or interface +## dispatch overhead and enabling inlining. +## This rule only reports violations when there are virtual calls or interface calls that can actually be avoided by +## using a concrete type. +dotnet_diagnostic.CA1859.severity = none + +## Avoid using 'Enumerable.Any()' extension method (CA1860) +## To determine whether a collection type has any elements, it's more efficient and clearer to use the Length, Count, or IsEmpty (if possible) properties than to call the xref:System.Linq.Enumerable.Any%2A?displayProperty=nameWithType method. +## Any(), which is an extension method, uses language integrated query (LINQ). It's more efficient to rely on the collection's own properties, and it also clarifies intent. +## [!NOTE] +## This rule is similar to CA1827: Do not use Count()/LongCount() when Any() can be used. However, that rule applies to the Linq Count() method, while this rule suggests using the Count property. +dotnet_diagnostic.CA1860.severity = silent + +## Avoid constant arrays as arguments (CA1861) +## Constant arrays passed as arguments are not reused when called repeatedly, which implies a new array is created each time. If the passed array is not mutated within the called method, consider extracting it to a static readonly field to improve performance. +## [!NOTE] +## If the called method mutates the passed array or if you're not sure if the method would mutate the array, don't extract the array to a static readonly field. Doing so could be a breaking change. In this case, it's better to suppress the warning instead. +dotnet_diagnostic.CA1861.severity = none + +## Prefer the 'IDictionary.TryAdd(TKey, TValue)' method (CA1864) +## Both xref:System.Collections.Generic.Dictionary%602.ContainsKey(%600)?displayProperty=nameWithType and xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType perform a lookup, which is redundant. xref:System.Collections.Generic.Dictionary%602.Add%2A?displayProperty=nameWithType also throws an exception if the key is already present in the dictionary. It's more efficient to call xref:System.Collections.Generic.Dictionary%602.TryAdd%2A?displayProperty=nameWithType, which returns a Boolean value that indicates if the value was added or not. TryAdd doesn't overwrite the key's value if the key is already present. +dotnet_diagnostic.CA1864.severity = warning + +## Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char (CA1865) +## The overload that takes a char parameter performs better than the overload that takes a string parameter. +dotnet_diagnostic.CA1865.severity = warning +dotnet_diagnostic.CA1866.severity = silent +dotnet_diagnostic.CA1867.severity = silent + +## Unnecessary call to 'Contains' for sets (CA1868) +## Both xref:System.Collections.Generic.ISet%601.Add(%600)?displayProperty=nameWithType and xref:System.Collections.Generic.ICollection%601.Remove(%600)?displayProperty=nameWithType perform a lookup, which makes it redundant to call xref:System.Collections.Generic.ICollection%601.Contains(%600)?displayProperty=nameWithType beforehand. It's more efficient to call xref:System.Collections.Generic.ISet%601.Add(%600) or xref:System.Collections.Generic.ICollection%601.Remove(%600) directly, which returns a Boolean value indicating whether the item was added or removed. +## This logic also applies to xref:System.Collections.Immutable.IImmutableSet%601.Add(%600)?displayProperty=nameWithType and xref:System.Collections.Immutable.IImmutableSet%601.Remove(%600)?displayProperty=nameWithType, except that they either return a new set if the item is added or removed, or the original set if it wasn't. +dotnet_diagnostic.CA1868.severity = suggestion + +## Cache and reuse 'JsonSerializerOptions' instances (CA1869) +## Using a local instance of xref:System.Text.Json.JsonSerializerOptions for serialization or deserialization can substantially degrade the performance of your application if your code executes multiple times since System.Text.Json internally caches serialization-related metadata into the provided instance. +dotnet_diagnostic.CA1869.severity = suggestion + +## Dispose objects before losing scope (CA2000) +## If a disposable object is not explicitly disposed before all references to it are out of scope, the object will be disposed at some indeterminate time when the garbage collector runs the finalizer of the object. Because an exceptional event might occur that will prevent the finalizer of the object from running, the object should be explicitly disposed instead. +dotnet_diagnostic.CA2000.severity = warning + +## Do not lock on objects with weak identity (CA2002) +## An object is said to have a weak identity when it can be directly accessed across application domain boundaries. A thread that tries to acquire a lock on an object that has a weak identity can be blocked by a second thread in a different application domain that has a lock on the same object. +## The following types have a weak identity and are flagged by the rule: +## xref:System.String +## Arrays of value types, including integral types, floating-point types, and xref:System.Boolean. +## xref:System.MarshalByRefObject +## xref:System.ExecutionEngineException +## xref:System.OutOfMemoryException +## xref:System.StackOverflowException +## xref:System.Reflection.MemberInfo +## xref:System.Reflection.ParameterInfo +## xref:System.Threading.Thread +## this or Me object +dotnet_diagnostic.CA2002.severity = warning + +## Do not directly await a Task (CA2007) +## When an asynchronous method awaits a xref:System.Threading.Tasks.Task directly, continuation usually occurs in the same thread that created the task, depending on the async context. This behavior can be costly in terms of performance and can result in a deadlock on the UI thread. Consider calling xref:System.Threading.Tasks.Task.ConfigureAwait(System.Boolean)?displayProperty=nameWithType to signal your intention for continuation. +dotnet_diagnostic.CA2007.severity = suggestion + +## Do not create tasks without passing a TaskScheduler (CA2008) +## The following .NET task creation and continuation methods have overloads that allow specifying or omitting a xref:System.Threading.Tasks.TaskScheduler instance: +## xref:System.Threading.Tasks.TaskFactory.StartNew%2A?displayProperty=fullName methods +## xref:System.Threading.Tasks.Task.ContinueWith%2A?displayProperty=fullName methods +## Always specify an explicit xref:System.Threading.Tasks.TaskScheduler argument to avoid the default xref:System.Threading.Tasks.TaskScheduler.Current%2A value, whose behavior is defined by the caller and may vary at run time. xref:System.Threading.Tasks.TaskScheduler.Current%2A returns the scheduler associated with whatever xref:System.Threading.Tasks.Task is currently running on that thread. If there is no such task, it returns xref:System.Threading.Tasks.TaskScheduler.Default%2A, which represents the thread pool. Using xref:System.Threading.Tasks.TaskScheduler.Current%2A could lead to deadlocks or UI responsiveness issues in some situations, when it was intended to create the task on the thread pool, but instead it waits to get back onto the UI thread. +## For further information and detailed examples, see New TaskCreationOptions and TaskContinuationOptions in .NET Framework 4.5. +## [!NOTE] +## VSTHRD105 - Avoid method overloads that assume TaskScheduler.Current is a similar rule implemented in Microsoft.VisualStudio.Threading.Analyzers package. dotnet_diagnostic.CA2008.severity = none -dotnet_diagnostic.CA2009.severity = warning + +## Do not call ToImmutableCollection on an ImmutableCollection value (CA2009) +## xref:System.Collections.Immutable namespace contains types that define immutable collections. This rule analyzes the following immutable collection types: +## xref:System.Collections.Immutable.ImmutableArray%601?displayProperty=fullName +## xref:System.Collections.Immutable.ImmutableList%601?displayProperty=fullName +## xref:System.Collections.Immutable.ImmutableHashSet%601?displayProperty=fullName +## xref:System.Collections.Immutable.ImmutableSortedSet%601?displayProperty=fullName +## xref:System.Collections.Immutable.ImmutableDictionary%602?displayProperty=fullName +## xref:System.Collections.Immutable.ImmutableSortedDictionary%602?displayProperty=fullName +## These types define extension methods that create a new immutable collection from an existing xref:System.Collections.Generic.IEnumerable%601 collection. +## xref:System.Collections.Immutable.ImmutableArray%601 defines xref:System.Collections.Immutable.ImmutableArray.ToImmutableArray%2A. +## xref:System.Collections.Immutable.ImmutableList%601 defines xref:System.Collections.Immutable.ImmutableList.ToImmutableList%2A. +## xref:System.Collections.Immutable.ImmutableHashSet%601 defines xref:System.Collections.Immutable.ImmutableHashSet.ToImmutableHashSet%2A. +## xref:System.Collections.Immutable.ImmutableSortedSet%601 defines xref:System.Collections.Immutable.ImmutableSortedSet.ToImmutableSortedSet%2A. +## xref:System.Collections.Immutable.ImmutableDictionary%602 defines xref:System.Collections.Immutable.ImmutableDictionary.ToImmutableDictionary%2A. +## xref:System.Collections.Immutable.ImmutableSortedDictionary%602 defines xref:System.Collections.Immutable.ImmutableSortedDictionary.ToImmutableSortedDictionary%2A. +## These extension methods are designed to convert a mutable collection to an immutable collection. However, the caller might accidentally pass in an immutable collection as input to these methods. This can represent a performance and/or a functional issue. +## Performance issue: Unnecessary boxing, unboxing, and/or runtime type checks on an immutable collection. +## Potential functional issue: Caller assumed to be operating on a mutable collection, when it actually had an immutable collection. +dotnet_diagnostic.CA2009.severity = suggestion + +## Do not assign property within its setter (CA2011) +## Assigning a property to itself in its set accessor leads to an infinite chain of recursive calls to the set accessor. This results in a xref:System.StackOverflowException at run time. Such a mistake is common when the property and the backing field to store the property value have similar names. Instead of assigning the value to the backing field, it was accidentally assigned to the property itself. dotnet_diagnostic.CA2011.severity = warning + +## Use ValueTasks correctly (CA2012) +## xref:System.Threading.Tasks.ValueTask instances returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance. dotnet_diagnostic.CA2012.severity = warning + +## Do not use ReferenceEquals with value types (CA2013) +## When comparing values using xref:System.Object.ReferenceEquals%2A, if objA and objB are value types, they are boxed before they are passed to the xref:System.Object.ReferenceEquals%2A method. This means that even if both objA and objB represent the same instance of a value type, the xref:System.Object.ReferenceEquals%2A method nevertheless returns false, as the following example shows. dotnet_diagnostic.CA2013.severity = warning + +## Do not use stackalloc in loops (CA2014) +## The C# stackalloc expression allocates memory from the current stack frame, and that memory may not be released until the current method call returns. If stackalloc is used in a loop, it can lead to stack overflows due to exhausting the stack memory. dotnet_diagnostic.CA2014.severity = warning -dotnet_diagnostic.CA2015.severity = warning -dotnet_diagnostic.CA2016.severity = suggestion + +## Do not define finalizers for types derived from MemoryManager (CA2015) +## Adding a finalizer to a type derived from xref:System.Buffers.MemoryManager%601 is likely an indication of a bug, as it suggests a native resource that could have been handed out in a xref:System.Span%601 is getting cleaned up and potentially while it is still in use by the xref:System.Span%601. +## [!NOTE] +## The xref:System.Buffers.MemoryManager%601 class is intended for advanced scenarios. Most developers do not need to use it. +dotnet_diagnostic.CA2015.severity = suggestion + +## Forward the CancellationToken parameter to methods that take one (CA2016) +## This rule analyzes method definitions that take a CancellationToken as their last parameter, then analyzes all methods invoked in its body. If any of the method invocations can either accept a CancellationToken as the last parameter, or have an overload that takes a CancellationToken as the last parameter, then the rule suggests using that option instead to ensure that the cancellation notification gets propagated to all operations that can listen to it. +## [!NOTE] +## Rule CA2016 is available in all .NET versions where the CancellationToken type is available. For the applicable versions, see the CancellationToken "Applies to" section. +dotnet_diagnostic.CA2016.severity = warning + +## Parameter count mismatch (CA2017) +## This rule flags logger calls that have an incorrect number of message arguments. dotnet_diagnostic.CA2017.severity = warning + +## The count argument to Buffer.BlockCopy should specify the number of bytes to copy (CA2018) +## When using Buffer.BlockCopy, the count argument specifies the number of bytes to copy. You should only use Array.Length for the count argument on arrays whose elements are exactly one byte in size. byte, sbyte, and bool arrays have elements that are one byte in size. dotnet_diagnostic.CA2018.severity = warning -dotnet_diagnostic.CA2100.severity = warning + +## ThreadStatic fields should not use inline initialization (CA2019) +## xref:System.ThreadStaticAttribute fields should be initialized lazily on use and not with inline initialization or explicitly in a static (Shared in Visual Basic) constructor. A static constructor only initializes the field on the thread that runs the type's static constructor. +dotnet_diagnostic.CA2019.severity = warning + +## Prevent behavioral change caused by built-in operators of IntPtr/UIntPtr (CA2020) +## With the numeric IntPtr feature, xref:System.IntPtr and xref:System.UIntPtr gained built-in operators for conversions, unary operations, and binary operations. These operators might throw when overflowing within checked context or may not throw in unchecked context compared to the previous user-defined operators in .NET 6 and earlier versions. You might encounter this behavioral change when upgrading to .NET 7. +dotnet_diagnostic.CA2020.severity = none + +## Review SQL queries for security vulnerabilities (CA2100) +## This rule assumes that any string, whose value can't be determined at compile time, may contain user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks. In a SQL injection attack, a malicious user supplies input that alters the design of a query in an attempt to damage or gain unauthorized access to the underlying database. Typical techniques include injection of a single quotation mark or apostrophe, which is the SQL literal string delimiter; two dashes, which signifies a SQL comment; and a semicolon, which indicates that a new command follows. If user input must be part of the query, use one of the following, listed in order of effectiveness, to reduce the risk of attack. +## Use a stored procedure. +## Use a parameterized command string. +## Validate the user input for both type and content before you build the command string. +## The following .NET types implement the xref:System.Data.IDbCommand.CommandText%2A property or provide constructors that set the property by using a string argument. +## xref:System.Data.Odbc.OdbcCommand?displayProperty=fullName and xref:System.Data.Odbc.OdbcDataAdapter?displayProperty=fullName +## xref:System.Data.OleDb.OleDbCommand?displayProperty=fullName and xref:System.Data.OleDb.OleDbDataAdapter?displayProperty=fullName +## xref:System.Data.OracleClient.OracleCommand?displayProperty=fullName and xref:System.Data.OracleClient.OracleDataAdapter?displayProperty=fullName +## xref:System.Data.SqlClient.SqlCommand?displayProperty=fullName and xref:System.Data.SqlClient.SqlDataAdapter?displayProperty=fullName +## In some cases, this rule might not determine a string's value at compile time, even though you can. In those cases, this rule produces false positives when using those strings as SQL commands. The following is an example of such a string. +## int x = 10; +## string query = "SELECT TOP " + x.ToString() + " FROM Table"; +## The same applies when using ToString() implicitly. +## int x = 10; +## string query = String.Format("SELECT TOP {0} FROM Table", x); +dotnet_diagnostic.CA2100.severity = none + +## Specify marshalling for P/Invoke string arguments (CA2101) +## When you convert from Unicode to ANSI, it is possible that not all Unicode characters can be represented in a specific ANSI code page. Best-fit mapping tries to solve this problem by substituting a character for the character that cannot be represented. The use of this feature can cause a potential security vulnerability because you cannot control the character that is chosen. For example, malicious code could intentionally create a Unicode string that contains characters that are not found in a particular code page, which are converted to file system special characters such as '..' or '/'. Note also that security checks for special characters frequently occur before the string is converted to ANSI. +## Best-fit mapping is the default for the unmanaged conversion, WChar to MByte. Unless you explicitly disable best-fit mapping, your code might contain an exploitable security vulnerability because of this issue. +## [!CAUTION] +## Code Access Security (CAS) should not be considered a security boundary. dotnet_diagnostic.CA2101.severity = none -dotnet_diagnostic.CA2201.severity = suggestion -# dotnet_diagnostic.CA2201.severity = warning -dotnet_diagnostic.CA2207.severity = warning -dotnet_diagnostic.CA2208.severity = warning -dotnet_diagnostic.CA2211.severity = suggestion + +## Review visible event handlers (CA2109) +## An externally visible event-handling method presents a security issue that requires review. +## Do not expose event-handling methods unless absolutely necessary. An event handler, a delegate type, that invokes the exposed method can be added to any event as long as the handler and event signatures match. Events can potentially be raised by any code, and are frequently raised by highly trusted system code in response to user actions such as clicking a button. Adding a security check to an event-handling method does not prevent code from registering an event handler that invokes the method. +## A demand cannot reliably protect a method invoked by an event handler. Security demands help protect code from untrusted callers by examining the callers on the call stack. Code that adds an event handler to an event is not necessarily present on the call stack when the event handler's methods run. Therefore, the call stack might have only highly trusted callers when the event handler method is invoked. This causes demands made by the event handler method to succeed. Also, the demanded permission might be asserted when the method is invoked. For these reasons, the risk of not fixing a violation of this rule can only be assessed after reviewing the event-handling method. When you review your code, consider the following issues: +## Does your event handler perform any operations that are dangerous or exploitable, such as asserting permissions or suppressing unmanaged code permission? +## What are the security threats to and from your code because it can run at any time with only highly trusted callers on the stack? +dotnet_diagnostic.CA2109.severity = none + +## Seal methods that satisfy private interfaces (CA2119) +## Interface methods have public accessibility, which cannot be changed by the implementing type. An internal interface creates a contract that is not intended to be implemented outside the assembly that defines the interface. A public type that implements a method of an internal interface using the virtual (Overridable in Visual Basic) modifier allows the method to be overridden by a derived type that is outside the assembly. If a second type in the defining assembly calls the method and expects an internal-only contract, behavior might be compromised when, instead, the overridden method in the outside assembly is executed. This creates a security vulnerability. +dotnet_diagnostic.CA2119.severity = none + +## Avoid handling Corrupted State Exceptions (CA2153) +## CSE indicates that the state of a process has been corrupted and not caught by the system. In the corrupted state scenario, a general handler only catches the exception if you mark your method with the xref:System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute?displayProperty=fullName attribute. By default, the Common Language Runtime (CLR) does not invoke catch handlers for CSEs. +## The safest option is to allow the process to crash without catching these kinds of exceptions. Even logging code can allow attackers to exploit memory corruption bugs. +## This warning triggers when catching CSEs with a general handler that catches all exceptions, for example, catch (System.Exception e) or catch with no exception parameter. +dotnet_diagnostic.CA2153.severity = none + +## Rethrow to preserve stack details (CA2200) +## Once an exception is thrown, part of the information it carries is the stack trace. The stack trace is a list of the method call hierarchy that starts with the method that throws the exception and ends with the method that catches the exception. If an exception is rethrown by specifying the exception in the throw statement, the stack trace is restarted at the current method and the list of method calls between the original method that threw the exception and the current method is lost. To keep the original stack trace information with the exception, use the throw statement without specifying the exception. +## If you're rethrowing the exception from somewhere other than the handler (catch block), use xref:System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(System.Exception)?displayProperty=nameWithType to capture the exception in the handler and xref:System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw?displayProperty=nameWithType when you want to rethrow it. For more information, see Capture exceptions to rethrow later. +dotnet_diagnostic.CA2200.severity = error + +## Do not raise reserved exception types (CA2201) +## The following exception types are too general to provide sufficient information to the user: +## xref:System.Exception?displayProperty=fullName +## xref:System.ApplicationException?displayProperty=fullName +## xref:System.SystemException?displayProperty=fullName +## The following exception types are reserved and should be thrown only by the common language runtime: +## xref:System.AccessViolationException?displayProperty=fullName +## xref:System.ExecutionEngineException?displayProperty=fullName +## xref:System.IndexOutOfRangeException?displayProperty=fullName +## xref:System.NullReferenceException?displayProperty=fullName +## xref:System.OutOfMemoryException?displayProperty=fullName +## xref:System.Runtime.InteropServices.COMException?displayProperty=fullName +## xref:System.Runtime.InteropServices.ExternalException?displayProperty=fullName +## xref:System.Runtime.InteropServices.SEHException?displayProperty=fullName +## xref:System.StackOverflowException?displayProperty=fullName +## Don't throw general exceptions +## If you throw a general exception type, such as xref:System.Exception or xref:System.SystemException, in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they don't know how to handle. +## Instead, either throw a more derived type that already exists in the framework, or create your own type that derives from xref:System.Exception. +## Throw specific exceptions +## The following table shows which exception to throw for various types of invalid arguments, including the value parameter in the set accessor of a property. +## Invalid argument Exception null reference xref:System.ArgumentNullException Outside the allowed range of values (such as an index for a collection or list) xref:System.ArgumentOutOfRangeException Invalid enum value xref:System.ComponentModel.InvalidEnumArgumentException Contains a format that doesn't meet the parameter specifications of a method (such as the format string for ToString(String)) xref:System.FormatException Otherwise invalid xref:System.ArgumentException +## The following table shows which exception to throw for various types of invalid operations. +## Invalid operation Exception Operation is invalid for the current state of an object. xref:System.InvalidOperationException Operation is performed on an object that has been disposed. xref:System.ObjectDisposedException Operation is not supported (such as in an overridden Stream.Write in a stream opened for reading). xref:System.NotSupportedException Conversion would result in an overflow (such as in an explicit cast operator overload). xref:System.OverflowException +## For all other situations, consider creating your own type that derives from xref:System.Exception and throw that. +dotnet_diagnostic.CA2201.severity = none + +## Initialize value type static fields inline (CA2207) +## When a value-type is declared, it undergoes a default initialization where all value-type fields are set to zero and all reference-type fields are set to null (Nothing in Visual Basic). An explicit static constructor is only guaranteed to run before an instance constructor or static member of the type is called. Therefore, if the type is created without calling an instance constructor, the static constructor is not guaranteed to run. +## If all static data is initialized inline and no explicit static constructor is declared, the C# and Visual Basic compilers add the beforefieldinit flag to the MSIL class definition. The compilers also add a private static constructor that contains the static initialization code. This private static constructor is guaranteed to run before any static fields of the type are accessed. +dotnet_diagnostic.CA2207.severity = none + +## Instantiate argument exceptions correctly (CA2208) +## Instead of calling the default constructor, call one of the constructor overloads that allows a more meaningful exception message to be provided. The exception message should target the developer and clearly explain the error condition and how to correct or avoid the exception. +## The signatures of the one and two string constructors of xref:System.ArgumentException and its derived types are not consistent with respect to the position message and paramName parameters. Make sure these constructors are called with the correct string arguments. The signatures are as follows: +## ArgumentException(string message) +## ArgumentException(string message, string paramName) +## ArgumentNullException(string paramName) +## ArgumentNullException(string paramName, string message) +## ArgumentOutOfRangeException(string paramName) +## ArgumentOutOfRangeException(string paramName, string message) +## DuplicateWaitObjectException(string parameterName) +## DuplicateWaitObjectException(string parameterName, string message) +dotnet_diagnostic.CA2208.severity = suggestion + +## Non-constant fields should not be visible (CA2211) +## Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques for synchronizing access to the class object. Because these are difficult skills to learn, and testing such an object poses its own challenges, static fields are best used to store data that does not change. This rule applies to libraries; applications should not expose any fields. +dotnet_diagnostic.CA2211.severity = warning + +## Disposable fields should be disposed (CA2213) +## A type is responsible for disposing of all its unmanaged resources. Rule CA2213 checks to see whether a disposable type (that is, one that implements xref:System.IDisposable) T declares a field F that is an instance of a disposable type FT. For each field F that's assigned a locally created object within the methods or initializers of the containing type T, the rule attempts to locate a call to FT.Dispose. The rule searches the methods called by T.Dispose and one level lower (that is, the methods called by the methods called by T.Dispose). +## [!NOTE] +## Other than the special cases, rule CA2213 fires only for fields that are assigned a locally created disposable object within the containing type's methods and initializers. If the object is created or assigned outside of type T, the rule does not fire. This reduces noise for cases where the containing type doesn't own the responsibility for disposing of the object. dotnet_diagnostic.CA2213.severity = warning -dotnet_diagnostic.CA2214.severity = suggestion + +## Do not call overridable methods in constructors (CA2214) +## When a virtual method is called, the actual type that executes the method is not selected until run time. When a constructor calls a virtual method, it's possible that the constructor for the instance that invokes the method has not executed. This could lead to errors or unexpected behavior, if an overridden virtual method relies on initialization and other configuration in the constructor. +dotnet_diagnostic.CA2214.severity = error + +## Dispose methods should call base class dispose (CA2215) +## If a type inherits from a disposable type, it must call the xref:System.IDisposable.Dispose%2A method of the base type from within its own xref:System.IDisposable.Dispose%2A method. Calling the base type Dispose method ensures that any resources created by the base type are released. dotnet_diagnostic.CA2215.severity = warning + +## Disposable types should declare finalizer (CA2216) +## A violation of this rule is reported if the disposable type contains fields of the following types: +## xref:System.IntPtr?displayProperty=fullName +## xref:System.UIntPtr?displayProperty=fullName +## xref:System.Runtime.InteropServices.HandleRef?displayProperty=fullName dotnet_diagnostic.CA2216.severity = none + +## Do not mark enums with FlagsAttribute (CA2217) +## An enumeration should have xref:System.FlagsAttribute present only if each value defined in the enumeration is a power of two or a combination of defined values. dotnet_diagnostic.CA2217.severity = none + +## Override GetHashCode on overriding Equals (CA2218) +## xref:System.Object.GetHashCode%2A returns a value, based on the current instance, that's suited for hashing algorithms and data structures such as hash tables. Two objects that are the same type and are equal must return the same hash code to ensure that instances of the following types work correctly: +## xref:System.Collections.Hashtable?displayProperty=fullName +## xref:System.Collections.SortedList?displayProperty=fullName +## xref:System.Collections.Generic.Dictionary%602?displayProperty=fullName +## xref:System.Collections.Generic.SortedDictionary%602?displayProperty=fullName +## xref:System.Collections.Generic.SortedList%602?displayProperty=fullName +## xref:System.Collections.Specialized.HybridDictionary?displayProperty=fullName +## xref:System.Collections.Specialized.ListDictionary?displayProperty=fullName +## xref:System.Collections.Specialized.OrderedDictionary?displayProperty=fullName +## Types that implement xref:System.Collections.Generic.IEqualityComparer%601?displayProperty=fullName +## [!NOTE] +## This rule only applies to Visual Basic code. The C# compiler generates a separate warning, CS0659. dotnet_diagnostic.CA2218.severity = warning + +## Do not raise exceptions in exception clauses (CA2219) +## When an exception is raised in an exception clause, it greatly increases the difficulty of debugging. +## When an exception is raised in a finally or fault clause, the new exception hides the active exception, if present. This makes the original error hard to detect and debug. +## When an exception is raised in a filter clause, the runtime silently catches the exception, and causes the filter to evaluate to false. There is no way to tell the difference between the filter evaluating to false and an exception being throw from a filter. This makes it hard to detect and debug errors in the filter's logic. dotnet_diagnostic.CA2219.severity = warning + +## Override Equals on overloading operator equals (CA2224) +## The equality operator is intended to be a syntactically convenient way to access the functionality of the xref:System.Object.Equals%2A method. If you implement the equality operator, its logic must be identical to that of xref:System.Object.Equals%2A. +## [!NOTE] +## This rule only applies to Visual Basic code. The C# compiler generates a separate warning, CS0660. dotnet_diagnostic.CA2224.severity = warning + +## Operator overloads have named alternates (CA2225) +## Operator overloading allows the use of symbols to represent computations for a type. For example, a type that overloads the plus symbol + for addition would typically have an alternative member named Add. The named alternative member provides access to the same functionality as the operator. It's provided for developers who program in languages that do not support overloaded operators. +## This rule examines: +## Implicit and explicit cast operators in a type by checking for methods named To and From. +## The operators listed in the following table: +## C# Visual Basic C++ Alternate method name + (binary) + + (binary) Add += += += Add & And & BitwiseAnd &= And= &= BitwiseAnd | Or | BitwiseOr |= Or= |= BitwiseOr -- N/A -- Decrement / / / Divide /= /= /= Divide == = == Equals ^ Xor ^ Xor ^= Xor= ^= Xor > > > CompareTo or Compare >= >= >= CompareTo or Compare ++ N/A ++ Increment != <> != Equals << << << LeftShift <<= <<= <<= LeftShift < < < CompareTo or Compare <= <= <= CompareTo or Compare && N/A && LogicalAnd || N/A || LogicalOr ! N/A ! LogicalNot % Mod % Mod or Remainder %= N/A %= Mod * (binary) * * Multiply *= N/A *= Multiply ~ Not ~ OnesComplement >> >> >> RightShift >>= N/A >>= RightShift - (binary) - (binary) - (binary) Subtract -= N/A -= Subtract true IsTrue N/A IsTrue (Property) - (unary) N/A - Negate + (unary) N/A + Plus false IsFalse False IsTrue (Property) +## *N/A means the operator cannot be overloaded in the selected language. +## [!NOTE] +## In C#, when a binary operator is overloaded, the corresponding assignment operator, if any, is also implicitly overloaded. dotnet_diagnostic.CA2225.severity = none -dotnet_diagnostic.CA2226.severity = suggestion + +## Operators should have symmetrical overloads (CA2226) +## There are no circumstances where either equality or inequality is applicable to instances of a type, and the opposite operator is undefined. Types typically implement the inequality operator by returning the negated value of the equality operator. +## The C# compiler issues an error for violations of this rule. +dotnet_diagnostic.CA2226.severity = warning + +## Collection properties should be read only (CA2227) +## A writable collection property allows a user to replace the collection with a completely different collection. A read-only or init-only property stops the collection from being replaced, but still allows the individual members to be set. If replacing the collection is a goal, the preferred design pattern is to include a method to remove all the elements from the collection, and a method to repopulate the collection. See the xref:System.Collections.ArrayList.Clear%2A and xref:System.Collections.ArrayList.AddRange%2A methods of the xref:System.Collections.ArrayList?displayProperty=fullName class for an example of this pattern. +## Both binary and XML serialization support read-only properties that are collections. The xref:System.Xml.Serialization.XmlSerializer?displayProperty=fullName class has specific requirements for types that implement xref:System.Collections.ICollection and xref:System.Collections.IEnumerable?displayProperty=fullName in order to be serializable. dotnet_diagnostic.CA2227.severity = warning + +## Implement serialization constructors (CA2229) +## This rule is relevant for types that support custom serialization. A type supports custom serialization if it implements the xref:System.Runtime.Serialization.ISerializable interface. The serialization constructor is required to deserialize, or recreate, objects that have been serialized using the xref:System.Runtime.Serialization.ISerializable.GetObjectData%2A?displayProperty=nameWithType method. dotnet_diagnostic.CA2229.severity = none -dotnet_diagnostic.CA2231.severity = suggestion -dotnet_diagnostic.CA2234.severity = silent + +## Overload operator equals on overriding ValueType.Equals (CA2231) +## In most programming languages, there is no default implementation of the equality operator (==) for value types. If your programming language supports operator overloads, you should consider implementing the equality operator. Its behavior should be identical to that of xref:System.Object.Equals%2A. +## You cannot use the default equality operator in an overloaded implementation of the equality operator. Doing so will cause a stack overflow. To implement the equality operator, use the Object.Equals method in your implementation. For example: +## If (Object.ReferenceEquals(left, Nothing)) Then +## Return Object.ReferenceEquals(right, Nothing) +## Else +## Return left.Equals(right) +## End If +## if (Object.ReferenceEquals(left, null)) +## return Object.ReferenceEquals(right, null); +## return left.Equals(right); +dotnet_diagnostic.CA2231.severity = warning + +## Pass System.Uri objects instead of strings (CA2234) +## A parameter name is split into tokens based on the camel casing convention, and then each token is checked to see whether it equals "uri", "Uri", "urn", "Urn", "url", or "Url". If there is a match, the parameter is assumed to represent a uniform resource identifier (URI). A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The xref:System.Uri class provides these services in a safe and secure manner. When there is a choice between two overloads that differ only regarding the representation of a URI, the user should choose the overload that takes a xref:System.Uri argument. +dotnet_diagnostic.CA2234.severity = suggestion + +## Mark all non-serializable fields (CA2235) +## A serializable type is one that is marked with the xref:System.SerializableAttribute?displayProperty=fullName attribute. When the type is serialized, a xref:System.Runtime.Serialization.SerializationException?displayProperty=fullName exception is thrown if the type contains an instance field of a type that's not serializable and doesn't implement the xref:System.Runtime.Serialization.ISerializable?displayProperty=fullName interface. +## [!TIP] +## CA2235 does not fire for instance fields of types that implement xref:System.Runtime.Serialization.ISerializable because they provide their own serialization logic. dotnet_diagnostic.CA2235.severity = none + +## Mark ISerializable types with SerializableAttribute (CA2237) +## To be recognized by the common language runtime as serializable, types must be marked with the xref:System.SerializableAttribute attribute even if the type uses a custom serialization routine through implementation of the xref:System.Runtime.Serialization.ISerializable interface. dotnet_diagnostic.CA2237.severity = none -dotnet_diagnostic.CA2241.severity = warning + +## Provide correct arguments to formatting methods (CA2241) +## The arguments to methods such as xref:System.Console.WriteLine%2A, xref:System.Console.Write%2A, and xref:System.String.Format%2A consist of a format string followed by several xref:System.Object?displayProperty=fullName instances. The format string consists of text and embedded format items of the form {index[,alignment][:formatString]}. 'index' is a zero-based integer that indicates which of the objects to format. If an object does not have a corresponding index in the format string, the object is ignored. If the object specified by 'index' does not exist, a xref:System.FormatException?displayProperty=fullName is thrown at run time. +dotnet_diagnostic.CA2241.severity = none + +## Test for NaN correctly (CA2242) +## xref:System.Double.NaN?displayProperty=fullName, which represents a value that's not a number, results when an arithmetic operation is undefined. Any expression that tests for equality between a value and xref:System.Double.NaN?displayProperty=fullName always returns false. Any expression that tests for inequality (!= in C#) between a value and xref:System.Double.NaN?displayProperty=fullName always returns true. dotnet_diagnostic.CA2242.severity = warning -dotnet_diagnostic.CA2243.severity = warning + +## Attribute string literals should parse correctly (CA2243) +## Since attributes are derived from xref:System.Attribute?displayProperty=fullName, and attributes are used at compile time, only constant values can be passed to their constructors. Attribute parameters that must represent URLs, GUIDs, and Versions cannot be typed as xref:System.Uri?displayProperty=fullName, xref:System.Guid?displayProperty=fullName, and xref:System.Version?displayProperty=fullName, because these types cannot be represented as constants. Instead, they must be represented by strings. +## Because the parameter is typed as a string, it is possible that an incorrectly formatted parameter could be passed at compile time. +## This rule uses a naming heuristic to find parameters that represent a uniform resource identifier (URI), a Globally Unique Identifier (GUID), or a Version, and verifies that the passed value is correct. +dotnet_diagnostic.CA2243.severity = none + +## Do not duplicate indexed element initializations (CA2244) +## Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. +## Indexed element initializers in object initializers must initialize unique elements. A duplicate index will overwrite a previous element initialization. dotnet_diagnostic.CA2244.severity = warning + +## Do not assign a property to itself (CA2245) +## C# compiler generates a warning CS1717: Assignment made to same variable; did you mean to assign something else? when a field, local or parameter symbol is assigned to itself. Such a mistake is common when a local, parameter, or field symbol has a name similar to another symbol in scope. Instead of using different symbols on the left-hand and right-hand side of the assignment, the same symbol was used on both sides. This leads to a redundant assignment of the value to itself and generally indicates a functional bug. +## Assigning a property to itself is also a similar functional bug for almost all real world cases. However, in some extreme corner cases, fetching a property value can have side effects and the property's new value is different from the original value. If so, property self-assignment is not redundant and cannot be removed. This prevents the compiler from generating a CS1717 warning for property self-assignment, without introducing a breaking change for these cases. +## Rule CA2245 aims at filling this gap. It reports the violation for property self-assignment to help fix these functional bugs. For the small set of corner cases where property self-assignment is desirable, CA2245 violations can be suppressed in source with an appropriate justification comment. dotnet_diagnostic.CA2245.severity = warning -dotnet_diagnostic.CA2246.severity = warning + +## Do not assign a symbol and its member in the same statement (CA2246) +## Assigning a symbol and its member, that is, a field or a property, in the same statement is not recommended. It is not clear if the member access was intended to use the symbol's old value prior to the assignment or the new value from the assignment in this statement. For clarity, the multi-assign statement must be split into two or more simple assignment statements. +dotnet_diagnostic.CA2246.severity = error + +## Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum (CA2247) +## The TaskCompletionSource type has a constructor that accepts a xref:System.Threading.Tasks.TaskCreationOptions?displayProperty=fullName enum value, and another constructor that accepts a xref:System.Object. Accidentally passing a xref:System.Threading.Tasks.TaskContinuationOptions?displayProperty=fullName enum value instead of a xref:System.Threading.Tasks.TaskCreationOptions?displayProperty=fullName enum value will result in calling the xref:System.Object-based constructor: it will compile and run, but it will not have the intended behavior. dotnet_diagnostic.CA2247.severity = warning + +## Provide correct enum argument to Enum.HasFlag (CA2248) +## The Enum.HasFlag method expects the enum argument to be of the same enum type as the instance on which the method is invoked. If these are different enum types, an unhandled exception will be thrown at run time. dotnet_diagnostic.CA2248.severity = warning + +## Consider using String.Contains instead of String.IndexOf (CA2249) +## When xref:System.String.IndexOf%2A is used to check if the result is equal to -1 or greater or equal than 0, the call can be safely substituted with xref:System.String.Contains%2A without an impact on performance. +## Depending on the xref:System.String.IndexOf%2A overload being used, the suggested fix could get a comparisonType argument added: +## Overload Suggested fix String.IndexOf(char) String.Contains(char) String.IndexOf(string) String.Contains(string, StringComparison.CurrentCulture) String.IndexOf(char, StringComparison.Ordinal) String.Contains(char) String.IndexOf(string, StringComparison.Ordinal) String.Contains(string) String.IndexOf(char, NON StringComparison.Ordinal)* String.Contains(char, NON StringComparison.Ordinal)* String.IndexOf(string, NON StringComparison.Ordinal)* String.Contains(string, NON StringComparison.Ordinal)* +## * Any StringComparison enum value other than StringComparison.Ordinal: +## xref:System.StringComparison.CurrentCulture +## xref:System.StringComparison.CurrentCultureIgnoreCase +## xref:System.StringComparison.InvariantCulture +## xref:System.StringComparison.InvariantCultureIgnoreCase +## xref:System.StringComparison.OrdinalIgnoreCase dotnet_diagnostic.CA2249.severity = warning + +## Use ThrowIfCancellationRequested (CA2250) +## You can accomplish the same thing by calling xref:System.Threading.CancellationToken.ThrowIfCancellationRequested?displayProperty=nameWithType. dotnet_diagnostic.CA2250.severity = warning + +## Use String.Equals over String.Compare (CA2251) +## xref:System.String.Compare%2A?displayProperty=nameWithType is designed to produce a total-order comparison that can be used for sorting. If you only care whether the strings are equal, it is both clearer and likely faster to use an equivalent overload of xref:System.String.Equals%2A?displayProperty=nameWithType. dotnet_diagnostic.CA2251.severity = warning + +## Opt in to preview features before using them (CA2252) +## When an API or assembly that's decorated with the xref:System.Runtime.Versioning.RequiresPreviewFeaturesAttribute attribute is consumed, this rule checks if the call site has opted in to preview features. A call site has opted in to preview features if one of the following applies: +## It is within the scope of a RequiresPreviewFeaturesAttribute annotation. +## It is part of an assembly or module that has already opted in to preview features. +## The following image shows an example of the CA2252 diagnostic. +## Code editor with CA2252 warning. +## Here, Lib is a preview type that's constructed in the Main method. Main itself is not annotated as a preview method, so diagnostics are produced on the two constructors calls inside Main. dotnet_diagnostic.CA2252.severity = none + +## Named placeholders should not be numeric values (CA2253) +## Named placeholders in the logging message template should not be comprised of only numeric characters. dotnet_diagnostic.CA2253.severity = warning -dotnet_diagnostic.CA2254.severity = none + +## Template should be a static expression (CA2254) +## When performing logging, it's desirable to preserve the structure of the log (including placeholder names) along with the placeholder values. Preserving this information allows for better observability and search in log aggregation and monitoring software. +## Preferred: +## var firstName = "Lorenz"; +## var lastName = "Otto"; +## +## // This tells the logger that there are FirstName and LastName properties +## // on the log message, and correlates them with the argument values. +## logger.Warning("Person {FirstName} {LastName} encountered an issue", firstName, lastName); +## Not preferred: +## // DO NOT DO THIS +## +## var firstName = "Lorenz"; +## var lastName = "Otto"; +## +## // Here, the log template itself is changing, and the association between named placeholders and their values is lost. +## logger.Warning("Person " + firstName + " " + lastName + " encountered an issue"); +## +## // String interpolation also loses the association between placeholder names and their values. +## logger.Warning($"Person {firstName} {lastName} encountered an issue"); +## The logging message template should not vary between calls. +dotnet_diagnostic.CA2254.severity = suggestion + +## The ModuleInitializer attribute should not be used in libraries (CA2255) +## Module initializers are intended to be used by application code to ensure an application's components are initialized before the application code begins executing. If library code declares a method with the xref:System.Runtime.CompilerServices.ModuleInitializerAttribute, it can interfere with application initialization and also lead to limitations in that application's trimming abilities. Library code should therefore not utilize the xref:System.Runtime.CompilerServices.ModuleInitializerAttribute attribute. dotnet_diagnostic.CA2255.severity = none + +## All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation-attributed interface (CA2256) +## Types attributed with xref:System.Runtime.InteropServices.DynamicInterfaceCastableImplementationAttribute act as an interface implementation for a type that implements the IDynamicInterfaceCastable type. As a result, it must provide an implementation of all of the members defined in the inherited interfaces, because the type that implements IDynamicInterfaceCastable will not provide them otherwise. dotnet_diagnostic.CA2256.severity = none + +## Members defined on an interface with the 'DynamicInterfaceCastableImplementationAttribute' should be 'static' (CA2257) +## Since a type that implements IDynamicInterfaceCastable may not implement a dynamic interface in metadata, calls to an instance interface member that is not an explicit implementation defined on this type are likely to fail at run time. To avoid run-time errors, mark new interface members static. dotnet_diagnostic.CA2257.severity = none + +## Providing a 'DynamicInterfaceCastableImplementation' interface in Visual Basic is unsupported (CA2258) +## Providing a functional interface that's attributed with DynamicInterfaceCastableImplementationAttribute requires the Default Interface Members feature, which is not supported in Visual Basic. dotnet_diagnostic.CA2258.severity = none -# Other +## Ensure ThreadStatic is only used with static fields (CA2259) +## xref:System.ThreadStaticAttribute, which indicates that the value of a field is unique for each thread, only affects static (Shared in Visual Basic) fields. When applied to instance fields, the attribute has no impact on behavior. +dotnet_diagnostic.CA2259.severity = warning + +## Implement generic math interfaces correctly (CA2260) +## Some generic math interfaces introduce static abstract members. The only way to access those static members is through a generic constraint that implements the "curiously recurring template pattern" (CRTP). Therefore, the derived type itself must be used for the self-recurring type parameter. If a type implements such an interface without passing the required type parameter and CA2260 is ignored, the code will compile successfully but the static abstract will not be accessible. Thus, the type will not be usable. The compiler emits a warning with ID CS0315 on such usage. +dotnet_diagnostic.CA2260.severity = warning + +## Do not use insecure deserializer BinaryFormatter (CA2300) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=nameWithType deserialization method calls or references. If you want to deserialize only when the xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Binder property is set to restrict types, disable this rule and enable rules CA2301 and CA2302 instead. Limiting which types can be deserialized can help mitigate against known remote code execution attacks, but your deserialization will still be vulnerable to denial of service attacks. +## [!INCLUDEbinaryformatter] +dotnet_diagnostic.CA2300.severity = none + +## Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder (CA2301) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=nameWithType deserialization method calls or references, when xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter doesn't have its xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Binder set. If you want to disallow any deserialization with xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter regardless of the xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Binder property, disable this rule and CA2302, and enable rule CA2300. +dotnet_diagnostic.CA2301.severity = none + +## Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize (CA2302) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=nameWithType deserialization method calls or references when the xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Binder might be null. If you want to disallow any deserialization with xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter regardless of the xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Binder property, disable this rule and CA2301, and enable rule CA2300. +dotnet_diagnostic.CA2302.severity = none + +## Do not use insecure deserializer LosFormatter (CA2305) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Web.UI.LosFormatter?displayProperty=nameWithType deserialization method calls or references. +## LosFormatter is insecure and can't be made secure. For more information, see the BinaryFormatter security guide. +dotnet_diagnostic.CA2305.severity = none + +## Do not use insecure deserializer NetDataContractSerializer (CA2310) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Runtime.Serialization.NetDataContractSerializer?displayProperty=nameWithType deserialization method calls or references. If you want to deserialize only when the xref:System.Runtime.Serialization.NetDataContractSerializer.Binder property is set to restrict types, disable this rule and enable rules CA2311 and CA2312 instead. Limiting which types can be deserialized can help mitigate against known remote code execution attacks, but your deserialization will still be vulnerable to denial of service attacks. +## NetDataContractSerializer is insecure and can't be made secure. For more information, see the BinaryFormatter security guide. +dotnet_diagnostic.CA2310.severity = none + +## Do not deserialize without first setting NetDataContractSerializer.Binder (CA2311) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Runtime.Serialization.NetDataContractSerializer?displayProperty=nameWithType deserialization method calls or references, when xref:System.Runtime.Serialization.NetDataContractSerializer doesn't have its xref:System.Runtime.Serialization.NetDataContractSerializer.Binder set. If you want to disallow any deserialization with xref:System.Runtime.Serialization.NetDataContractSerializer regardless of the xref:System.Runtime.Serialization.NetDataContractSerializer.Binder property, disable this rule and CA2312, and enable rule CA2310. +dotnet_diagnostic.CA2311.severity = none + +## Ensure NetDataContractSerializer.Binder is set before deserializing (CA2312) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Runtime.Serialization.NetDataContractSerializer?displayProperty=nameWithType deserialization method calls or references when the xref:System.Runtime.Serialization.NetDataContractSerializer.Binder might be null. If you want to disallow any deserialization with xref:System.Runtime.Serialization.NetDataContractSerializer regardless of the xref:System.Runtime.Serialization.NetDataContractSerializer.Binder property, disable this rule and CA2311, and enable rule CA2310. +## NetDataContractSerializer is insecure and can't be made secure. For more information, see the BinaryFormatter security guide. +dotnet_diagnostic.CA2312.severity = none + +## Do not use insecure deserializer ObjectStateFormatter (CA2315) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Web.UI.ObjectStateFormatter?displayProperty=nameWithType deserialization method calls or references. +dotnet_diagnostic.CA2315.severity = none + +## Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver (CA2321) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Web.Script.Serialization.JavaScriptSerializer?displayProperty=nameWithType deserialization method calls or references, after initializing the xref:System.Web.Script.Serialization.JavaScriptSerializer with a xref:System.Web.Script.Serialization.SimpleTypeResolver?displayProperty=nameWithType. +dotnet_diagnostic.CA2321.severity = none + +## Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing (CA2322) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds xref:System.Web.Script.Serialization.JavaScriptSerializer?displayProperty=nameWithType deserialization method calls or references, when the xref:System.Web.Script.Serialization.JavaScriptSerializer may have been initialized with a xref:System.Web.Script.Serialization.SimpleTypeResolver?displayProperty=nameWithType. +dotnet_diagnostic.CA2322.severity = none + +## Do not use TypeNameHandling values other than None (CA2326) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds Newtonsoft.Json.TypeNameHandling values other than None. If you want to deserialize only when a Newtonsoft.Json.Serialization.ISerializationBinder is specified to restrict deserialized types, disable this rule and enable rules CA2327, CA2328, CA2329, and CA2330 instead. +dotnet_diagnostic.CA2326.severity = none + +## Do not use insecure JsonSerializerSettings (CA2327) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds Newtonsoft.Json.JsonSerializerSettings instances that are configured to deserialize types specified from input, but not configured to restrict deserialized types with a Newtonsoft.Json.Serialization.ISerializationBinder. If you want to disallow deserialization of types specified from input completely, disable rules CA2327, CA2328, CA2329, and CA2330, and enable rule CA2326 instead. +dotnet_diagnostic.CA2327.severity = none + +## Ensure that JsonSerializerSettings are secure (CA2328) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds Newtonsoft.Json.JsonSerializerSettings instances that might be configured to deserialize types specified from input, but may not be configured to restrict deserialized types with a Newtonsoft.Json.Serialization.ISerializationBinder. If you want to disallow deserialization of types specified from input completely, disable rules CA2327, CA2328, CA2329, and CA2330, and enable rule CA2326 instead. +dotnet_diagnostic.CA2328.severity = none + +## Do not deserialize with JsonSerializer using an insecure configuration (CA2329) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds Newtonsoft.Json.JsonSerializer instances that are configured to deserialize types specified from input, but not configured to restrict deserialized types with a Newtonsoft.Json.Serialization.ISerializationBinder. If you want to disallow deserialization of types specified from input completely, disable rules CA2327, CA2328, CA2329, and CA2330, and enable rule CA2326 instead. +dotnet_diagnostic.CA2329.severity = none + +## Ensure that JsonSerializer has a secure configuration when deserializing (CA2330) +## [!INCLUDEinsecure-deserializers-description] +## This rule finds Newtonsoft.Json.JsonSerializer instances that might be configured to deserialize types specified from input, but may not be configured to restrict deserialized types with a Newtonsoft.Json.Serialization.ISerializationBinder. If you want to disallow deserialization of types specified from input completely, disable rules CA2327, CA2328, CA2329, and CA2330, and enable rule CA2326 instead. +dotnet_diagnostic.CA2330.severity = none + +## Ensure DataTable.ReadXml()'s input is trusted (CA2350) +## When deserializing a xref:System.Data.DataTable with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There may be unknown remote code execution vulnerabilities. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2350.severity = none + +## Ensure DataSet.ReadXml()'s input is trusted (CA2351) +## When deserializing a xref:System.Data.DataSet with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There may be unknown remote code execution vulnerabilities. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2351.severity = none + +## Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks (CA2352) +## When deserializing untrusted input with xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and the deserialized object graph contains a xref:System.Data.DataSet or xref:System.Data.DataTable, an attacker can craft a malicious payload to perform a remote code execution attack. +## This rule finds types which are insecure when deserialized. If your code doesn't deserialize the types found, then you don't have a deserialization vulnerability. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2352.severity = none + +## Unsafe DataSet or DataTable in serializable type (CA2353) +## When deserializing untrusted input and the deserialized object graph contains a xref:System.Data.DataSet or xref:System.Data.DataTable, an attacker can craft a malicious payload to perform a denial of service attack. There may be unknown remote code execution vulnerabilities. +## This rule finds types which are insecure when deserialized. If your code doesn't deserialize the types found, then you don't have a deserialization vulnerability. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2353.severity = none + +## Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attack (CA2354) +## When deserializing untrusted input with xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and the deserialized object graph contains a xref:System.Data.DataSet or xref:System.Data.DataTable, an attacker can craft a malicious payload to perform a remote code execution attack. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2354.severity = none + +## Unsafe DataSet or DataTable in deserialized object graph (CA2355) +## When deserializing untrusted input with xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and the deserialized object graph contains a xref:System.Data.DataSet or xref:System.Data.DataTable, an attacker can craft a malicious payload to perform a denial of service attack. There may be unknown remote code execution vulnerabilities. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2355.severity = none + +## Unsafe DataSet or DataTable type in web deserialized object graph (CA2356) +## When deserializing untrusted input and the deserialized object graph contains a xref:System.Data.DataSet or xref:System.Data.DataTable, an attacker can craft a malicious payload to perform a denial of service attack. There may be unknown remote code execution vulnerabilities. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2356.severity = none + +## Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data (CA2361) +## When deserializing a xref:System.Data.DataSet with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There may be unknown remote code execution vulnerabilities. +## This rule is like CA2351, but for autogenerated code for an in-memory representation of data within a GUI application. Usually, these autogenerated classes aren't deserialized from untrusted input. Your application's usage may vary. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2361.severity = none + +## Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks (CA2362) +## When deserializing untrusted input with xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter and the deserialized object graph contains a xref:System.Data.DataSet or xref:System.Data.DataTable, an attacker can craft a malicious payload to perform a remote code execution attack. +## This rule is like CA2352, but for autogenerated code for an in-memory representation of data within a GUI application. Usually, these autogenerated classes aren't deserialized from untrusted input. Your application's usage may vary. +## This rule finds types which are insecure when deserialized. If your code doesn't deserialize the types found, then you don't have a deserialization vulnerability. +## For more information, see DataSet and DataTable security guidance. +dotnet_diagnostic.CA2362.severity = none + +## Review code for SQL injection vulnerabilities (CA3001) +## When working with untrusted input and SQL commands, be mindful of SQL injection attacks. An SQL injection attack can execute malicious SQL commands, compromising the security and integrity of your application. Typical techniques include using a single quotation mark or apostrophe for delimiting literal strings, two dashes for a comment, and a semicolon for the end of a statement. For more information, see SQL Injection. +## This rule attempts to find input from HTTP requests reaching an SQL command's text. +## [!NOTE] +## This rule can't track data across assemblies. For example, if one assembly reads the HTTP request input and then passes it to another assembly that executes the SQL command, this rule won't produce a warning. +## [!NOTE] +## There is a configurable limit to how deep this rule will analyze data flow across method calls. See Analyzer Configuration for how to configure the limit in an EditorConfig file. +dotnet_diagnostic.CA3001.severity = none + +## Review code for XSS vulnerabilities (CA3002) +## When working with untrusted input from web requests, be mindful of cross-site scripting (XSS) attacks. An XSS attack injects untrusted input into raw HTML output, allowing the attacker to execute malicious scripts or maliciously modify content in your web page. A typical technique is putting