แก้ไข

แชร์ผ่าน


Code quality rules

.NET code analysis provides rules that aim to improve code quality. The rules are organized into areas such as design, globalization, performance, and security. Certain rules are specific to .NET API usage, while others are about generic code quality.

Index of rules

The following table lists code quality analysis rules.

Rule ID and warning Description
CA1000: Do not declare static members on generic types 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. In these two cases, the syntax for specifying the type argument is different and easily confused.
CA1001: Types that own disposable fields should be disposable A class declares and implements an instance field that is a System.IDisposable type, and the class does not implement IDisposable. A class that declares an IDisposable field indirectly owns an unmanaged resource and should implement the IDisposable interface.
CA1002: Do not expose generic lists System.Collections.Generic.List<(Of <(T>)>) is a generic collection that is designed for performance, not inheritance. Therefore, List does not contain any virtual members. The generic collections that are designed for inheritance should be exposed instead.
CA1003: Use generic event handler instances A type contains a delegate that returns void, whose signature contains two parameters (the first an object and the second a type that is assignable to EventArgs), and the containing assembly targets Microsoft .NET Framework 2.0.
CA1005: Avoid excessive parameters on generic types 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<T>, and in certain cases that have two type parameters, as in Dictionary<TKey, TValue>. However, if more than two type parameters exist, the difficulty becomes too great for most users.
CA1008: Enums should have zero value The default value of an uninitialized enumeration, just as other value types, is zero. A nonflags-attributed enumeration should define a member by using the value of zero so that the default value is a valid value of the enumeration. If an enumeration that has the FlagsAttribute attribute applied defines a zero-valued member, its name should be "None" to indicate that no values have been set in the enumeration.
CA1010: Collections should implement generic interface 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.
CA1012: Abstract types should not have public constructors 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.
CA1014: Mark assemblies with CLSCompliantAttribute 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 by using CLSCompliantAttribute . If this attribute is not present on an assembly, the assembly is not compliant.
CA1016: Mark assemblies with AssemblyVersionAttribute .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.
CA1017: Mark assemblies with ComVisibleAttribute ComVisibleAttribute determines how COM clients access managed code. Good design dictates that assemblies explicitly indicate COM visibility. COM visibility can be set for the whole assembly and then overridden for individual types and type members. If this attribute is not present, the contents of the assembly are visible to COM clients.
CA1018: Mark attributes with AttributeUsageAttribute When you define a custom attribute, mark it by using 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.
CA1019: Define accessors for attribute arguments 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. 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.
CA1021: Avoid out parameters 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.
CA1024: Use properties where appropriate A public or protected method has a name that starts with "Get", takes no parameters, and returns a value that is not an array. The method might be a good candidate to become a property.
CA1027: Mark enums with FlagsAttribute An enumeration is a value type that defines a set of related named constants. Apply FlagsAttribute to an enumeration when its named constants can be meaningfully combined.
CA1028: Enum storage should be Int32 An enumeration is a value type that defines a set of related named constants. By default, the System.Int32 data type is used to store the constant value. Although you can change this underlying type, it is not required or recommended for most scenarios.
CA1030: Use events where appropriate This rule detects methods that have names that ordinarily would be used for events. If a method is 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.
CA1031: Do not catch general exception types General exceptions should not be caught. Catch a more specific exception, or rethrow the general exception as the last statement in the catch block.
CA1032: Implement standard exception constructors Failure to provide the full set of constructors can make it difficult to correctly handle exceptions.
CA1033: Interface methods should be callable by child types An unsealed externally visible type provides an explicit method implementation of a public interface and does not provide an alternative externally visible method that has the same name.
CA1034: Nested types should not be visible A nested type is a type that is declared in the scope of another type. Nested types are useful to encapsulate private implementation details of the containing type. Used for this purpose, nested types should not be externally visible.
CA1036: Override methods on comparable types A public or protected type implements the System.IComparable interface. It does not override Object.Equals nor does it overload the language-specific operator for equality, inequality, less than, or greater than.
CA1040: Avoid empty interfaces 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.
CA1041: Provide ObsoleteAttribute message A type or member is marked by using a System.ObsoleteAttribute attribute that does not have its ObsoleteAttribute.Message property specified. When a type or member that is marked by using ObsoleteAttribute is compiled, the Message property of the attribute is displayed. This gives the user information about the obsolete type or member.
CA1043: Use integral or string argument for indexers Indexers (that is, indexed properties) should use integral or string types for the index. These types are typically used for indexing data structures and they increase the usability of the library. Use of the Object type should be restricted to those cases where the specific integral or string type cannot be specified at design time.
CA1044: Properties should not be write only 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 that value, does not provide any security. Also, without read access, the state of shared objects cannot be viewed, which limits their usefulness.
CA1045: Do not pass types by reference 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. Library architects who design for a general audience should not expect users to become proficient in working with out or ref parameters.
CA1046: Do not overload operator equals on reference types 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.
CA1047: Do not declare protected members in sealed types Types declare protected members so that inheriting types can access or override the member. By definition, sealed types cannot be inherited, which means that protected methods on sealed types cannot be called.
CA1050: Declare types in namespaces Types are declared in namespaces to prevent name collisions and as a way to organize related types in an object hierarchy.
CA1051: Do not declare visible instance fields 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.
CA1052: Static holder types should be sealed A public or protected type contains only static members and is not declared by using the sealed (C# Reference) (NotInheritable) modifier. A type that is not meant to be inherited should be marked by using the sealed modifier to prevent its use as a base type.
CA1053: Static holder types should not have constructors A public or nested public type declares only static members and has a public or protected default constructor. The constructor is unnecessary because calling static members does not require an instance of the type. The string overload should call the uniform resource identifier (URI) overload by using the string argument for safety and security.
CA1054: URI parameters should not be strings If a method takes a string representation of a URI, a corresponding overload should be provided that takes an instance of the URI class, which provides these services in a safe and secure manner.
CA1055: URI return values should not be strings This rule assumes that the method returns a URI. A string representation of a URI is prone to parsing and encoding errors, and can lead to security vulnerabilities. The System.Uri class provides these services in a safe and secure manner.
CA1056: URI properties should not be strings This 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 System.Uri class provides these services in a safe and secure manner.
CA1058: Types should not extend certain base types An externally visible type extends certain base types. Use one of the alternatives.
CA1060: Move P/Invokes to NativeMethods class Platform Invocation methods, such as those that are marked by using the System.Runtime.InteropServices.DllImportAttribute attribute, or methods that are defined by using the Declare keyword in Visual Basic, access unmanaged code. These methods should be of the NativeMethods, SafeNativeMethods, or UnsafeNativeMethods class.
CA1061: Do not hide base class methods 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.
CA1062: Validate arguments of public methods All reference arguments that are passed to externally visible methods should be checked against null.
CA1063: Implement IDisposable correctly All IDisposable types should implement the Dispose pattern correctly.
CA1064: Exceptions should be public An internal exception is visible only 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 Exception, SystemException, or ApplicationException, the external code will not have sufficient information to know what to do with the exception.
CA1065: Do not raise exceptions in unexpected locations A method that is not expected to throw exceptions throws an exception.
CA1066: Implement IEquatable when overriding Equals A value type overrides Equals method, but does not implement IEquatable<T>.
CA1067: Override Equals when implementing IEquatable A type implements IEquatable<T>, but does not override Equals method.
CA1068: CancellationToken parameters must come last A method has a CancellationToken parameter that is not the last parameter.
CA1069: Enums should not have duplicate values An enumeration has multiple members which are explicitly assigned the same constant value.
CA1070: Do not declare event fields as virtual A field-like event was declared as virtual.
CA1200: Avoid using cref tags with a prefix 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.
CA1303: Do not pass literals as localized parameters An externally visible method passes a string literal as a parameter to a .NET constructor or method, and that string should be localizable.
CA1304: Specify CultureInfo A method or constructor calls a member that has an overload that accepts a System.Globalization.CultureInfo parameter, and the method or constructor does not call the overload that takes the CultureInfo parameter. When a CultureInfo or System.IFormatProvider 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.
CA1305: Specify IFormatProvider A method or constructor calls one or more members that have overloads that accept a System.IFormatProvider parameter, and the method or constructor does not call the overload that takes the IFormatProvider parameter. When a System.Globalization.CultureInfo or IFormatProvider 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.
CA1307: Specify StringComparison for clarity A string comparison operation uses a method overload that does not set a StringComparison parameter.
CA1308: Normalize strings to uppercase Strings should be normalized to uppercase. A small group of characters cannot make a round trip when they are converted to lowercase.
CA1309: Use ordinal StringComparison A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable.
CA1310: Specify StringComparison for correctness A string comparison operation uses a method overload that does not set a StringComparison parameter and uses culture-specific string comparison by default.
CA1311: Specify a culture or use an invariant version Specify a culture or use an invariant culture to avoid implicit dependency on the current culture when calling ToUpper or ToLower.
CA1401: P/Invokes should not be visible A public or protected method in a public type has the System.Runtime.InteropServices.DllImportAttribute attribute (also implemented by the Declare keyword in Visual Basic). Such methods should not be exposed.
CA1416: Validate platform compatibility Using platform-dependent APIs on a component makes the code no longer work across all platforms.
CA1417: Do not use OutAttribute on string parameters for P/Invokes String parameters passed by value with the OutAttribute can destabilize the runtime if the string is an interned string.
CA1418: Use valid platform string Platform compatibility analyzer requires a valid platform name and version.
CA1419: Provide a parameterless constructor that is as visible as the containing type for concrete types derived from 'System.Runtime.InteropServices.SafeHandle' Providing a parameterless constructor that is as visible as the containing type for a type derived from System.Runtime.InteropServices.SafeHandle enables better performance and usage with source-generated interop solutions.
CA1420: Property, type, or attribute requires runtime marshalling Using features that require runtime marshalling when runtime marshalling is disabled will result in run-time exceptions.
CA1421: Method uses runtime marshalling when DisableRuntimeMarshallingAttribute is applied A method uses runtime marshalling, and runtime marshalling is explicitly disabled.
CA1422: Validate platform compatibility 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.
CA1501: Avoid excessive inheritance A type is more than four levels deep in its inheritance hierarchy. Deeply nested type hierarchies can be difficult to follow, understand, and maintain.
CA1502: Avoid excessive complexity This rule measures the number of linearly independent paths through the method, which is determined by the number and complexity of conditional branches.
CA1505: Avoid unmaintainable code A type or method has a low maintainability index value. A low maintainability index indicates that a type or method is probably difficult to maintain and would be a good candidate for redesign.
CA1506: Avoid excessive class coupling This rule measures class coupling by counting the number of unique type references that a type or method contains.
CA1507: Use nameof in place of string A string literal is used as an argument where a nameof expression could be used.
CA1508: Avoid dead conditional code A method has conditional code that always evaluates to true or false at run time. This leads to dead code in the false branch of the condition.
CA1509: Invalid entry in code metrics configuration file Code metrics rules, such as CA1501, CA1502, CA1505 and CA1506, supplied a configuration file named CodeMetricsConfig.txt that has an invalid entry.
CA1510: Use ArgumentNullException throw helper Throw helpers are simpler and more efficient than if blocks that construct a new exception instance.
CA1511: Use ArgumentException throw helper Throw helpers are simpler and more efficient than if blocks that construct a new exception instance.
CA1512: Use ArgumentOutOfRangeException throw helper Throw helpers are simpler and more efficient than if blocks that construct a new exception instance.
CA1513: Use ObjectDisposedException throw helper Throw helpers are simpler and more efficient than if blocks that construct a new exception instance.
CA1514: Avoid redundant length argument A redundant length argument is used when slicing to the end of a string or buffer. A calculated length can be error-prone and is also unnecessary.
CA1515: Consider making public types internal Unlike a class library, an application's API isn't typically referenced publicly, so types can be marked internal.
CA1700: Do not name enum values 'Reserved' 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.
CA1707: Identifiers should not contain underscores By convention, identifier names do not contain the underscore (_) character. This rule checks namespaces, types, members, and parameters.
CA1708: Identifiers should differ by more than case 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.
CA1710: Identifiers should have correct suffix By convention, the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, have a suffix that is associated with the base type or interface.
CA1711: Identifiers should not have incorrect suffix By convention, only the names of types that extend certain base types or that implement certain interfaces, or types that are derived from these types, should end with specific reserved suffixes. Other type names should not use these reserved suffixes.
CA1712: Do not prefix enum values with type name Names of enumeration members are not prefixed by using the type name because development tools are expected to provide type information.
CA1713: Events should not have before or after prefix The name of an event starts with "Before" or "After". 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.
CA1714: Flags enums should have plural names A public enumeration has the System.FlagsAttribute attribute, and its name does not end in "s". Types that are marked by using FlagsAttribute have names that are plural because the attribute indicates that more than one value can be specified.
CA1715: Identifiers should have correct prefix The name of an externally visible interface does not start with an uppercase "I". The name of a generic type parameter on an externally visible type or method does not start with an uppercase "T".
CA1716: Identifiers should not match keywords A namespace name or a type name matches a reserved keyword in a programming language. Identifiers for namespaces and types should not match keywords that are defined by languages that target the common language runtime.
CA1717: Only FlagsAttribute enums should have plural names Naming conventions dictate that a plural name for an enumeration indicates that more than one value of the enumeration can be specified at the same time.
CA1720: Identifiers should not contain type names The name of a parameter in an externally visible member contains a data type name, or the name of an externally visible member contains a language-specific data type name.
CA1721: Property names should not match get methods The name of a public or protected member starts with "Get" and otherwise matches the name of a public or protected property. "Get" methods and properties should have names that clearly distinguish their function.
CA1724: Type Names Should Not Match Namespaces Type names should not match the names of .NET namespaces. Violating this rule can reduce the usability of the library.
CA1725: Parameter names should match base declaration 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.
CA1727: Use PascalCase for named placeholders Use PascalCase for named placeholders in the logging message template.
CA1801: Review unused parameters A method signature includes a parameter that is not used in the method body.
CA1802: Use Literals Where Appropriate A field is declared static and read-only (Shared and ReadOnly in Visual Basic), and is initialized by using a value that is computable at compile time. Because the value that is assigned to the targeted field is computable at compile time, change the declaration to a const (Const in Visual Basic) field so that the value is computed at compile time instead of at run time.
CA1805: Do not initialize unnecessarily 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 is redundant, which adds to maintenance costs and might degrade performance (such as with increased assembly size).
CA1806: Do not ignore method results A new object is created but never used; or a method that creates and returns a new string is called and the new string is never used; or a COM or P/Invoke method returns an HRESULT or error code that is never used.
CA1810: Initialize reference type static fields inline 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 constructor checks can decrease performance.
CA1812: Avoid uninstantiated internal classes An instance of an assembly-level type is not created by code in the assembly.
CA1813: Avoid unsealed attributes .NET provides methods for retrieving custom attributes. By default, these methods search the attribute inheritance hierarchy. Sealing the attribute eliminates the search through the inheritance hierarchy and can improve performance.
CA1814: Prefer jagged arrays over multidimensional A jagged array is an array whose elements are arrays. The arrays that make up the elements can be of different sizes, leading to less wasted space for some sets of data.
CA1815: Override equals and operator equals on value types For value types, the inherited implementation of Equals uses the Reflection library and compares 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 to use instances as hash table keys, your value type should implement Equals.
CA1816: Call GC.SuppressFinalize correctly A method that is an implementation of Dispose does not call GC.SuppressFinalize; or a method that is not an implementation of Dispose calls GC.SuppressFinalize; or a method calls GC.SuppressFinalize and passes something other than this (Me in Visual Basic).
CA1819: Properties should not return arrays Arrays that are returned by properties are not write-protected, even when the property is read-only. To keep the array tamper-proof, the property must return a copy of the array. Typically, users will not understand the adverse performance implications of calling such a property.
CA1820: Test for empty strings using string length Comparing strings by using the String.Length property or the String.IsNullOrEmpty method is significantly faster than using Equals.
CA1821: Remove empty finalizers Whenever you can, avoid finalizers because of the additional performance overhead that is involved in tracking object lifetime. An empty finalizer incurs added overhead and delivers no benefit.
CA1822: Mark members as static 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. This can give you a measurable performance gain for performance-sensitive code.
CA1823: Avoid unused private fields Private fields were detected that do not appear to be accessed in the assembly.
CA1824: Mark assemblies with NeutralResourcesLanguageAttribute The NeutralResourcesLanguage attribute informs the resource manager of the language that was used to display the resources of a neutral culture for an assembly. This improves lookup performance for the first resource that you load and can reduce your working set.
CA1825: Avoid zero-length array allocations Initializing a zero-length array leads to unnecessary memory allocation. Instead, use the statically allocated empty array instance by calling Array.Empty. The memory allocation is shared across all invocations of this method.
CA1826: Use property instead of Linq Enumerable method Enumerable LINQ method was used on a type that supports an equivalent, more efficient property.
CA1827: Do not use Count/LongCount when Any can be used Count or LongCount method was used where Any method would be more efficient.
CA1828: Do not use CountAsync/LongCountAsync when AnyAsync can be used CountAsync or LongCountAsync method was used where AnyAsync method would be more efficient.
CA1829: Use Length/Count property instead of Enumerable.Count method Count LINQ method was used on a type that supports an equivalent, more efficient Length or Count property.
CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder Append and Insert provide overloads for multiple types beyond String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload.
CA1831: Use AsSpan instead of Range-based indexers for string when appropriate When using a range-indexer on a string and implicitly assigning the value to ReadOnlySpan<char> type, the method Substring will be used instead of Slice, which produces a copy of requested portion of the string.
CA1832: Use AsSpan or AsMemory instead of Range-based indexers for getting ReadOnlySpan or ReadOnlyMemory portion of an array When using a range-indexer on an array and implicitly assigning the value to a ReadOnlySpan<T> or ReadOnlyMemory<T> type, the method GetSubArray will be used instead of Slice, which produces a copy of requested portion of the array.
CA1833: Use AsSpan or AsMemory instead of Range-based indexers for getting Span or Memory portion of an array When using a range-indexer on an array and implicitly assigning the value to a Span<T> or Memory<T> type, the method GetSubArray will be used instead of Slice, which produces a copy of requested portion of the array.
CA1834: Use StringBuilder.Append(char) for single character strings StringBuilder has an Append overload that takes a char as its argument. Prefer calling the char overload for performance reasons.
CA1835: Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' 'Stream' has a 'ReadAsync' overload that takes a 'Memory<Byte>' as the first argument, and a 'WriteAsync' overload that takes a 'ReadOnlyMemory<Byte>' as the first argument. Prefer calling the memory based overloads, which are more efficient.
CA1836: Prefer IsEmpty over Count when available Prefer IsEmpty property that is more efficient than Count, Length, Count<TSource>(IEnumerable<TSource>) or LongCount<TSource>(IEnumerable<TSource>) to determine whether the object contains or not any items.
CA1837: Use Environment.ProcessId instead of Process.GetCurrentProcess().Id Environment.ProcessId is simpler and faster than Process.GetCurrentProcess().Id.
CA1838: Avoid StringBuilder parameters for P/Invokes Marshalling of 'StringBuilder' always creates a native buffer copy, resulting in multiple allocations for one marshalling operation.
CA1839: Use Environment.ProcessPath instead of Process.GetCurrentProcess().MainModule.FileName Environment.ProcessPath is simpler and faster than Process.GetCurrentProcess().MainModule.FileName.
CA1840: Use Environment.CurrentManagedThreadId instead of Thread.CurrentThread.ManagedThreadId Environment.CurrentManagedThreadId is more compact and efficient than Thread.CurrentThread.ManagedThreadId.
CA1841: Prefer Dictionary Contains methods Calling Contains on the Keys or Values collection might often be more expensive than calling ContainsKey or ContainsValue on the dictionary itself.
CA1842: Do not use 'WhenAll' with a single task Using WhenAll with a single task might result in performance loss. Await or return the task instead.
CA1843: Do not use 'WaitAll' with a single task Using WaitAll with a single task might result in performance loss. Await or return the task instead.
CA1844: Provide memory-based overrides of async methods when subclassing 'Stream' To improve performance, override the memory-based async methods when subclassing 'Stream'. Then implement the array-based methods in terms of the memory-based methods.
CA1845: Use span-based 'string.Concat' It is more efficient to use AsSpan and string.Concat, instead of Substring and a concatenation operator.
CA1846: Prefer AsSpan over Substring AsSpan is more efficient than Substring. Substring performs an O(n) string copy, while AsSpan does not and has a constant cost. AsSpan also does not perform any heap allocations.
CA1847: Use char literal for a single character lookup Use String.Contains(char) instead of String.Contains(string) when searching for a single character.
CA1848: Use the LoggerMessage delegates For improved performance, use the LoggerMessage delegates.
CA1849: Call async methods when in an async method In a method which is already asynchronous, calls to other methods should be to their async versions, where they exist.
CA1850: Prefer static HashData method over ComputeHash It's more efficient to use the static HashData method over creating and managing a HashAlgorithm instance to call ComputeHash.
CA1851: Possible multiple enumerations of IEnumerable collection Possible multiple enumerations of IEnumerable collection. Consider using an implementation that avoids multiple enumerations.
CA1852: Seal internal types A type that's not accessible outside its assembly and has no subtypes within its containing assembly is not sealed.
CA1853: Unnecessary call to 'Dictionary.ContainsKey(key)' There's no need to guard Dictionary.Remove(key) with Dictionary.ContainsKey(key). Dictionary<TKey,TValue>.Remove(TKey) already checks whether the key exists and doesn't throw if it doesn't exist.
CA1854: Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method Prefer 'TryGetValue' over a Dictionary indexer access guarded by a 'ContainsKey' check. 'ContainsKey' and the indexer both look up the key, so using 'TryGetValue' avoids the extra lookup.
CA1855: Use Span<T>.Clear() instead of Span<T>.Fill() It's more efficient to call Span<T>.Clear() than to call Span<T>.Fill(T) to fill the elements of the span with a default value.
CA1856: Incorrect usage of ConstantExpected attribute The ConstantExpectedAttribute attribute is not applied correctly on a parameter.
CA1857: The parameter expects a constant for optimal performance An invalid argument is passed to a parameter that's annotated with ConstantExpectedAttribute.
CA1858: Use StartsWith instead of IndexOf It's more efficient to call String.StartsWith than to call String.IndexOf to check whether a string starts with a given prefix.
CA1859: Use concrete types when possible for improved performance Code uses interface types or abstract types, leading to unnecessary interface calls or virtual calls.
CA1860: Avoid using 'Enumerable.Any()' extension method It's more efficient and clearer to use Length, Count, or IsEmpty (if possible) than to call Enumerable.Any to determine whether a collection type has any elements.
CA1861: Avoid constant arrays as arguments Constant arrays passed as arguments are not reused which implies a performance overhead. Consider extracting them to 'static readonly' fields to improve performance.
CA1862: Use the 'StringComparison' method overloads to perform case-insensitive string comparisons When code calls ToLower() or ToUpper() to perform a case-insensitive string comparison, an unnecessary allocation is performed.
CA1863: Use 'CompositeFormat' To reduce the formatting cost, cache and use a CompositeFormat instance as the argument to String.Format or StringBuilder.AppendFormat.
CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method Both Dictionary<TKey,TValue>.ContainsKey(TKey) and Dictionary<TKey,TValue>.Add perform a lookup, which is redundant. It's is more efficient to call Dictionary<TKey,TValue>.TryAdd, which returns a bool indicating if the value was added or not. TryAdd doesn't overwrite the key's value if the key is already present.
CA1865-CA1867: Use char overload The char overload is a better performing overload for a string with a single char.
CA1868: Unnecessary call to 'Contains' for sets Both ISet<T>.Add(T) and ICollection<T>.Remove(T) perform a lookup, which makes it redundant to call ICollection<T>.Contains(T) beforehand. It's more efficient to call Add(T) or Remove(T) directly, which returns a Boolean value indicating whether the item was added or removed.
CA1869: Cache and reuse 'JsonSerializerOptions' instances Using a local instance of 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.
CA1870: Use a cached 'SearchValues' instance Using a cached SearchValues<T> instance is more efficient than passing values to 'IndexOfAny' or 'ContainsAny' directly.
CA1871: Do not pass a nullable struct to 'ArgumentNullException.ThrowIfNull' 'ArgumentNullException.ThrowIfNull' accepts an 'object', so passing a nullable struct might cause the value to be boxed.
CA1872: Prefer 'Convert.ToHexString' and 'Convert.ToHexStringLower' over call chains based on 'BitConverter.ToString' Use Convert.ToHexString or Convert.ToHexStringLower when encoding bytes to a hexadecimal string representation. These methods are more efficient and allocation-friendly than using BitConverter.ToString in combination with String.Replace to replace dashes and String.ToLower.
CA2000: Dispose objects before losing scope Because an exceptional event might occur that will prevent the finalizer of an object from running, the object should be explicitly disposed before all references to it are out of scope.
CA2002: Do not lock on objects with weak identity 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.
CA2007: Do not directly await a Task An asynchronous method awaits a Task directly. When an asynchronous method awaits a Task directly, continuation occurs in the same thread that created the task. This behavior can be costly in terms of performance and can result in a deadlock on the UI thread. Consider calling Task.ConfigureAwait(Boolean) to signal your intention for continuation.
CA2008: Do not create tasks without passing a TaskScheduler A task creation or continuation operation uses a method overload that does not specify a TaskScheduler parameter.
CA2009: Do not call ToImmutableCollection on an ImmutableCollection value ToImmutable method was unnecessarily called on an immutable collection from System.Collections.Immutable namespace.
CA2011: Do not assign property within its setter A property was accidentally assigned a value within its own set accessor.
CA2012: Use ValueTasks correctly ValueTasks 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 might result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and might degrade performance.
CA2013: Do not use ReferenceEquals with value types When comparing values using System.Object.ReferenceEquals, if objA and objB are value types, they are boxed before they are passed to the ReferenceEquals method. This means that even if both objA and objB represent the same instance of a value type, the ReferenceEquals method nevertheless returns false.
CA2014: Do not use stackalloc in loops. Stack space allocated by a stackalloc is only released at the end of the current method's invocation. Using it in a loop can result in unbounded stack growth and eventual stack overflow conditions.
CA2015: Do not define finalizers for types derived from MemoryManager<T> Adding a finalizer to a type derived from MemoryManager<T> might permit memory to be freed while it is still in use by a Span<T>.
CA2016: Forward the CancellationToken parameter to methods that take one Forward the CancellationToken parameter to methods that take one to ensure the operation cancellation notifications gets properly propagated, or pass in CancellationToken.None explicitly to indicate intentionally not propagating the token.
CA2017: Parameter count mismatch Number of parameters supplied in the logging message template do not match the number of named placeholders.
CA2018: The count argument to Buffer.BlockCopy should specify the number of bytes to copy 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.
CA2019: ThreadStatic fields should not use inline initialization A field that's annotated with ThreadStaticAttribute is initialized inline or explicitly in a static (Shared in Visual Basic) constructor.
CA2020: Prevent behavioral change caused by built-in operators of IntPtr/UIntPtr Some built-in operators added in .NET 7 behave differently than the user-defined operators in .NET 6 and earlier versions. Some operators that used to throw in unchecked context while overflowing don't throw anymore unless wrapped within checked context. Some operators that previously didn't throw in checked context now throw unless wrapped within unchecked context.
CA2021: Don't call Enumerable.Cast<T> or Enumerable.OfType<T> with incompatible types A call to Enumerable.Cast<TResult>(IEnumerable) or Enumerable.OfType<TResult>(IEnumerable) specifies a type parameter that's incompatible with the type of the input collection.
CA2022: Avoid inexact read with Stream.Read A call to Stream.Read might return fewer bytes than requested, resulting in unreliable code if the return value isn't checked.
CA2100: Review SQL queries for security vulnerabilities A method sets the System.Data.IDbCommand.CommandText property by using a string that is built from a string argument to the method. This rule assumes that the string argument contains user input. A SQL command string that is built from user input is vulnerable to SQL injection attacks.
CA2101: Specify marshalling for P/Invoke string arguments A platform invoke member allows partially trusted callers, has a string parameter, and does not explicitly marshal the string. This can cause a potential security vulnerability.
CA2109: Review visible event handlers A public or protected event-handling method was detected. Event-handling methods should not be exposed unless absolutely necessary.
CA2119: Seal methods that satisfy private interfaces An inheritable public type provides an overridable method implementation of an internal (Friend in Visual Basic) interface. To fix a violation of this rule, prevent the method from being overridden outside the assembly.
CA2153: Avoid handling Corrupted State Exceptions Corrupted State Exceptions (CSEs) indicate that memory corruption exists in your process. Catching these rather than allowing the process to crash can lead to security vulnerabilities if an attacker can place an exploit into the corrupted memory region.
CA2200: Rethrow to preserve stack details An exception is rethrown and the exception is explicitly specified in the throw statement. If an exception is rethrown by specifying the exception in the throw statement, the list of method calls between the original method that threw the exception and the current method is lost.
CA2201: Do not raise reserved exception types This makes the original error difficult to detect and debug.
CA2207: Initialize value type static fields inline A value type declares an explicit static constructor. To fix a violation of this rule, initialize all static data when it is declared and remove the static constructor.
CA2208: Instantiate argument exceptions correctly A call is made to the default (parameterless) constructor of an exception type that is or derives from ArgumentException, or an incorrect string argument is passed to a parameterized constructor of an exception type that is or derives from ArgumentException.
CA2211: Non-constant fields should not be visible 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 to synchronize access to the class object.
CA2213: Disposable fields should be disposed A type that implements System.IDisposable declares fields that are of types that also implement IDisposable. The Dispose method of the field is not called by the Dispose method of the declaring type.
CA2214: Do not call overridable methods in constructors When a constructor calls a virtual method, the constructor for the instance that invokes the method might not have executed.
CA2215: Dispose methods should call base class dispose If a type inherits from a disposable type, it must call the Dispose method of the base type from its own Dispose method.
CA2216: Disposable types should declare finalizer A type that implements System.IDisposable and has fields that suggest the use of unmanaged resources does not implement a finalizer, as described by Object.Finalize.
CA2217: Do not mark enums with FlagsAttribute An externally visible enumeration is marked by using FlagsAttribute, and it has one or more values that are not powers of two or a combination of the other defined values on the enumeration.
CA2218: Override GetHashCode on overriding Equals A public type overrides System.Object.Equals but does not override System.Object.GetHashCode.
CA2219: Do not raise exceptions in exception clauses When an exception is raised in a finally or fault clause, the new exception hides the active exception. When an exception is raised in a filter clause, the runtime silently catches the exception. This makes the original error difficult to detect and debug.
CA2224: Override equals on overloading operator equals A public type implements the equality operator but doesn't override System.Object.Equals.
CA2225: Operator overloads have named alternates An operator overload was detected, and the expected named alternative method was not found. The named alternative member provides access to the same functionality as the operator and is provided for developers who program in languages that do not support overloaded operators.
CA2226: Operators should have symmetrical overloads A type implements the equality or inequality operator and does not implement the opposite operator.
CA2227: Collection properties should be read only A writable collection property allows a user to replace the collection with a different collection. A read-only property stops the collection from being replaced but still allows the individual members to be set.
CA2229: Implement serialization constructors To fix a violation of this rule, implement the serialization constructor. For a sealed class, make the constructor private; otherwise, make it protected.
CA2231: Overload operator equals on overriding ValueType.Equals A value type overrides Object.Equals but does not implement the equality operator.
CA2234: Pass System.Uri objects instead of strings A call is made to a method that has a string parameter whose name contains "uri", "URI", "urn", "URN", "url", or "URL". The declaring type of the method contains a corresponding method overload that has a System.Uri parameter.
CA2235: Mark all non-serializable fields An instance field of a type that is not serializable is declared in a type that is serializable.
CA2237: Mark ISerializable types with SerializableAttribute To be recognized by the common language runtime as serializable, types must be marked by using the SerializableAttribute attribute even when the type uses a custom serialization routine through implementation of the ISerializable interface.
CA2241: Provide correct arguments to formatting methods The format argument that is passed to System.String.Format does not contain a format item that corresponds to each object argument, or vice versa.
CA2242: Test for NaN correctly This expression tests a value against Single.Nan or Double.Nan. Use Single.IsNan(Single) or Double.IsNan(Double) to test the value.
CA2243: Attribute string literals should parse correctly The string literal parameter of an attribute does not parse correctly for a URL, a GUID, or a version.
CA2244: Do not duplicate indexed element initializations An object initializer has more than one indexed element initializer with the same constant index. All but the last initializer are redundant.
CA2245: Do not assign a property to itself A property was accidentally assigned to itself.
CA2246: Do not assign a symbol and its member in the same statement 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.
CA2247: Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum. TaskCompletionSource has constructors that take TaskCreationOptions that control the underlying Task, and constructors that take object state that's stored in the task. Accidentally passing a TaskContinuationOptions instead of a TaskCreationOptions will result in the call treating the options as state.
CA2248: Provide correct enum argument to Enum.HasFlag The enum type passed as an argument to the HasFlag method call is different from the calling enum type.
CA2249: Consider using String.Contains instead of String.IndexOf Calls to string.IndexOf where the result is used to check for the presence/absence of a substring can be replaced by string.Contains.
CA2250: Use ThrowIfCancellationRequested ThrowIfCancellationRequested automatically checks whether the token has been canceled, and throws an OperationCanceledException if it has.
CA2251: Use String.Equals over String.Compare It is both clearer and likely faster to use String.Equals instead of comparing the result of String.Compare to zero.
CA2252: Opt in to preview features Opt in to preview features before using preview APIs.
CA2253: Named placeholders should not be numeric values Named placeholders in the logging message template should not be comprised of only numeric characters.
CA2254: Template should be a static expression The logging message template should not vary between calls.
CA2255: The ModuleInitializer attribute should not be used in libraries Module initializers are intended to be used by application code to ensure an application's components are initialized before the application code begins executing.
CA2256: All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation-attributed interface Types attributed with 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.
CA2257: Members defined on an interface with 'DynamicInterfaceCastableImplementationAttribute' should be 'static' Since a type that implements IDynamicInterfaceCastable might 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. Mark new interface members static to avoid run-time errors.
CA2258: Providing a 'DynamicInterfaceCastableImplementation' interface in Visual Basic is unsupported Providing a functional DynamicInterfaceCastableImplementationAttribute-attributed interface requires the Default Interface Members feature, which is unsupported in Visual Basic.
CA2259: Ensure ThreadStatic is only used with static fields ThreadStaticAttribute only affects static (Shared in Visual Basic) fields. When applied to instance fields, the attribute has no impact on behavior.
CA2260: Implement generic math interfaces correctly Generic math interfaces require the derived type itself to be used for the self-recurring type parameter.
CA2261: Do not use ConfigureAwaitOptions.SuppressThrowing with Task<TResult> The ConfigureAwaitOptions.SuppressThrowing option isn't supported by the generic Task<TResult>, since that might lead to returning an invalid TResult.
CA2262: Set MaxResponseHeadersLength properly Make sure the MaxResponseHeadersLength value is provided correctly. This value is measured in kilobytes.
CA2263: Prefer generic overload when type is known Using a generic overload is preferable to passing a System.Type argument when the type is known, because they promote cleaner and more type-safe code with improved compile-time checks.
CA2264: Do not pass a non-nullable value to 'ArgumentNullException.ThrowIfNull' 'ArgumentNullException.ThrowIfNull' throws when the passed argument is 'null'. Certain constructs like non-nullable structs, and 'nameof()' and 'new' expressions are known to never be null, so 'ArgumentNullException.ThrowIfNull' will never throw.
CA2265: Do not compare Span<T> to null or default Comparing a span to null or default might not do what you intended. default and the null literal are implicitly converted to Span<T>.Empty.
CA2300: Do not use insecure deserializer BinaryFormatter Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2301: Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2302: Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2305: Do not use insecure deserializer LosFormatter Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2310: Do not use insecure deserializer NetDataContractSerializer Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2311: Do not deserialize without first setting NetDataContractSerializer.Binder Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2312: Ensure NetDataContractSerializer.Binder is set before deserializing Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2315: Do not use insecure deserializer ObjectStateFormatter Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2321: Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2322: Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2326: Do not use TypeNameHandling values other than None Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2327: Do not use insecure JsonSerializerSettings Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2328: Ensure that JsonSerializerSettings are secure Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2329: Do not deserialize with JsonSerializer using an insecure configuration Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2330: Ensure that JsonSerializer has a secure configuration when deserializing Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects.
CA2350: Ensure DataTable.ReadXml()'s input is trusted When deserializing a DataTable with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There might be unknown remote code execution vulnerabilities.
CA2351: Ensure DataSet.ReadXml()'s input is trusted When deserializing a DataSet with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There might be unknown remote code execution vulnerabilities.
CA2352: Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks A class or struct marked with SerializableAttribute contains a DataSet or DataTable field or property, and doesn't have a GeneratedCodeAttribute.
CA2353: Unsafe DataSet or DataTable in serializable type A class or struct marked with an XML serialization attribute or a data contract attribute contains a DataSet or DataTable field or property.
CA2354: Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attack Deserializing with an System.Runtime.Serialization.IFormatter serialized, and the casted type's object graph can include a DataSet or DataTable.
CA2355: Unsafe DataSet or DataTable in deserialized object graph Deserializing when the casted or specified type's object graph can include a DataSet or DataTable.
CA2356: Unsafe DataSet or DataTable in web deserialized object graph A method with a System.Web.Services.WebMethodAttribute or System.ServiceModel.OperationContractAttribute has a parameter that might reference a DataSet or DataTable.
CA2361: Ensure autogenerated class containing DataSet.ReadXml() is not used with untrusted data When deserializing a DataSet with untrusted input, an attacker can craft malicious input to perform a denial of service attack. There might be unknown remote code execution vulnerabilities.
CA2362: Unsafe DataSet or DataTable in autogenerated serializable type can be vulnerable to remote code execution attacks When deserializing untrusted input with BinaryFormatter and the deserialized object graph contains a DataSet or DataTable, an attacker can craft a malicious payload to perform a remote code execution attack.
CA3001: Review code for SQL injection vulnerabilities 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.
CA3002: Review code for XSS vulnerabilities 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.
CA3003: Review code for file path injection vulnerabilities When working with untrusted input from web requests, be mindful of using user-controlled input when specifying paths to files.
CA3004: Review code for information disclosure vulnerabilities Disclosing exception information gives attackers insight into the internals of your application, which can help attackers find other vulnerabilities to exploit.
CA3005: Review code for LDAP injection vulnerabilities When working with untrusted input, be mindful of Lightweight Directory Access Protocol (LDAP) injection attacks. An attacker can potentially run malicious LDAP statements against information directories. Applications that use user input to construct dynamic LDAP statements to access directory services are particularly vulnerable.
CA3006: Review code for process command injection vulnerabilities When working with untrusted input, be mindful of command injection attacks. A command injection attack can execute malicious commands on the underlying operating system, compromising the security and integrity of your server.
CA3007: Review code for open redirect vulnerabilities When working with untrusted input, be mindful of open redirect vulnerabilities. An attacker can exploit an open redirect vulnerability to use your website to give the appearance of a legitimate URL, but redirect an unsuspecting visitor to a phishing or other malicious webpage.
CA3008: Review code for XPath injection vulnerabilities When working with untrusted input, be mindful of XPath injection attacks. Constructing XPath queries using untrusted input might allow an attacker to maliciously manipulate the query to return an unintended result, and possibly disclose the contents of the queried XML.
CA3009: Review code for XML injection vulnerabilities When working with untrusted input, be mindful of XML injection attacks.
CA3010: Review code for XAML injection vulnerabilities When working with untrusted input, be mindful of XAML injection attacks. XAML is a markup language that directly represents object instantiation and execution. That means elements created in XAML can interact with system resources (for example, network access and file system IO).
CA3011: Review code for DLL injection vulnerabilities When working with untrusted input, be mindful of loading untrusted code. If your web application loads untrusted code, an attacker might be able to inject malicious DLLs into your process and execute malicious code.
CA3012: Review code for regex injection vulnerabilities When working with untrusted input, be mindful of regex injection attacks. An attacker can use regex injection to maliciously modify a regular expression, to make the regex match unintended results, or to make the regex consume excessive CPU resulting in a Denial of Service attack.
CA3061: Do not add schema by URL Do not use the unsafe overload of the Add method because it might cause dangerous external references.
CA3075: Insecure DTD Processing If you use insecure DTDProcessing instances or reference external entity sources, the parser might accept untrusted input and disclose sensitive information to attackers.
CA3076: Insecure XSLT Script Execution If you execute Extensible Stylesheet Language Transformations (XSLT) in .NET applications insecurely, the processor might resolve untrusted URI references that could disclose sensitive information to attackers, leading to Denial of Service and Cross-Site attacks.
CA3077: Insecure Processing in API Design, XML Document and XML Text Reader When designing an API derived from XMLDocument and XMLTextReader, be mindful of DtdProcessing. Using insecure DTDProcessing instances when referencing or resolving external entity sources or setting insecure values in the XML might lead to information disclosure.
CA3147: Mark verb handlers with ValidateAntiForgeryToken When designing an ASP.NET MVC controller, be mindful of cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET MVC controller.
CA5350: Do Not Use Weak Cryptographic Algorithms Weak encryption algorithms and hashing functions are used today for a number of reasons, but they should not be used to guarantee the confidentiality or integrity of the data they protect. This rule triggers when it finds TripleDES, SHA1, or RIPEMD160 algorithms in the code.
CA5351: Do Not Use Broken Cryptographic Algorithms Broken cryptographic algorithms are not considered secure and their use should be strongly discouraged. This rule triggers when it finds the MD5 hash algorithm or either the DES or RC2 encryption algorithms in code.
CA5358: Do Not Use Unsafe Cipher Modes Do Not Use Unsafe Cipher Modes
CA5359: Do not disable certificate validation A certificate can help authenticate the identity of the server. Clients should validate the server certificate to ensure requests are sent to the intended server. If the ServerCertificateValidationCallback always returns true, any certificate will pass validation.
CA5360: Do not call dangerous methods in deserialization Insecure deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application, inflict a Denial-of-Service (DoS) attack, or even execute arbitrary code upon it being deserialized. It's frequently possible for malicious users to abuse these deserialization features when the application is deserializing untrusted data which is under their control. Specifically, invoke dangerous methods in the process of deserialization. Successful insecure deserialization attacks could allow an attacker to carry out attacks such as DoS attacks, authentication bypasses, and remote code execution.
CA5361: Do not disable Schannel use of strong crypto Setting Switch.System.Net.DontEnableSchUseStrongCrypto to true weakens the cryptography used in outgoing Transport Layer Security (TLS) connections. Weaker cryptography can compromise the confidentiality of communication between your application and the server, making it easier for attackers to eavesdrop sensitive data.
CA5362: Potential reference cycle in deserialized object graph If deserializing untrusted data, then any code processing the deserialized object graph needs to handle reference cycles without going into infinite loops. This includes both code that's part of a deserialization callback and code that processes the object graph after deserialization completed. Otherwise, an attacker could perform a Denial-of-Service attack with malicious data containing a reference cycle.
CA5363: Do not disable request validation Request validation is a feature in ASP.NET that examines HTTP requests and determines whether they contain potentially dangerous content that can lead to injection attacks, including cross-site-scripting.
CA5364: Do not use deprecated security protocols Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Older protocol versions of TLS are less secure than TLS 1.2 and TLS 1.3 and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk.
CA5365: Do Not Disable HTTP Header Checking HTTP header checking enables encoding of the carriage return and newline characters, \r and \n, that are found in response headers. This encoding can help to avoid injection attacks that exploit an application that echoes untrusted data contained by the header.
CA5366: Use XmlReader For DataSet Read XML Using a DataSet to read XML with untrusted data might load dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD processing disabled.
CA5367: Do Not Serialize Types With Pointer Fields This rule checks whether there's a serializable class with a pointer field or property. Members that can't be serialized can be a pointer, such as static members or fields marked with NonSerializedAttribute.
CA5368: Set ViewStateUserKey For Classes Derived From Page Setting the ViewStateUserKey property can help you prevent attacks on your application by allowing you to assign an identifier to the view-state variable for individual users so that attackers cannot use the variable to generate an attack. Otherwise, there will be vulnerabilities to cross-site request forgery.
CA5369: Use XmlReader for Deserialize Processing untrusted DTD and XML schemas might enable loading dangerous external references, which should be restricted by using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled.
CA5370: Use XmlReader for validating reader Processing untrusted DTD and XML schemas might enable loading dangerous external references. This dangerous loading can be restricted by using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled.
CA5371: Use XmlReader for schema read Processing untrusted DTD and XML schemas might enable loading dangerous external references. Using an XmlReader with a secure resolver or with DTD and XML inline schema processing disabled restricts this.
CA5372: Use XmlReader for XPathDocument Processing XML from untrusted data might load dangerous external references, which can be restricted by using an XmlReader with a secure resolver or with DTD processing disabled.
CA5373: Do not use obsolete key derivation function This rule detects the invocation of weak key derivation methods System.Security.Cryptography.PasswordDeriveBytes and Rfc2898DeriveBytes.CryptDeriveKey. System.Security.Cryptography.PasswordDeriveBytes used a weak algorithm PBKDF1.
CA5374: Do Not Use XslTransform This rule checks if System.Xml.Xsl.XslTransform is instantiated in the code. System.Xml.Xsl.XslTransform is now obsolete and shouldn't be used.
CA5375: Do not use account shared access signature An account SAS can delegate access to read, write, and delete operations on blob containers, tables, queues, and file shares that are not permitted with a service SAS. However, it doesn't support container-level policies and has less flexibility and control over the permissions that are granted. Once malicious users get it, your storage account will be compromised easily.
CA5376: Use SharedAccessProtocol HttpsOnly SAS is sensitive data that can't be transported in plain text on HTTP.
CA5377: Use container level access policy A container-level access policy can be modified or revoked at any time. It provides greater flexibility and control over the permissions that are granted.
CA5378: Do not disable ServicePointManagerSecurityProtocols Setting Switch.System.ServiceModel.DisableUsingServicePointManagerSecurityProtocols to true limits Windows Communication Framework's (WCF) Transport Layer Security (TLS) connections to using TLS 1.0. That version of TLS will be deprecated.
CA5379: Do not use weak key derivation function algorithm The Rfc2898DeriveBytes class defaults to using the SHA1 algorithm. You should specify the hash algorithm to use in some overloads of the constructor with SHA256 or higher. Note, HashAlgorithm property only has a get accessor and doesn't have a overridden modifier.
CA5380: Do not add certificates to root store This rule detects code that adds a certificate into the Trusted Root Certification Authorities certificate store. By default, the Trusted Root Certification Authorities certificate store is configured with a set of public CAs that has met the requirements of the Microsoft Root Certificate Program.
CA5381: Ensure certificates are not added to root store This rule detects code that potentially adds a certificate into the Trusted Root Certification Authorities certificate store. By default, the Trusted Root Certification Authorities certificate store is configured with a set of public certification authorities (CAs) that has met the requirements of the Microsoft Root Certificate Program.
CA5382: Use secure cookies in ASP.NET Core Applications available over HTTPS must use secure cookies, which indicate to the browser that the cookie should only be transmitted using Secure Sockets Layer (SSL).
CA5383: Ensure use secure cookies in ASP.NET Core Applications available over HTTPS must use secure cookies, which indicate to the browser that the cookie should only be transmitted using Secure Sockets Layer (SSL).
CA5384: Do not use digital signature algorithm (DSA) DSA is a weak asymmetric encryption algorithm.
CA5385: Use Rivest–Shamir–Adleman (RSA) algorithm with sufficient key size An RSA key smaller than 2048 bits is more vulnerable to brute force attacks.
CA5386: Avoid hardcoding SecurityProtocolType value Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Protocol versions TLS 1.0 and TLS 1.1 are deprecated, while TLS 1.2 and TLS 1.3 are current. In the future, TLS 1.2 and TLS 1.3 might be deprecated. To ensure that your application remains secure, avoid hardcoding a protocol version and target at least .NET Framework v4.7.1.
CA5387: Do not use weak key derivation function with insufficient iteration count This rule checks if a cryptographic key was generated by Rfc2898DeriveBytes with an iteration count of less than 100,000. A higher iteration count can help mitigate against dictionary attacks that try to guess the generated cryptographic key.
CA5388: Ensure sufficient iteration count when using weak key derivation function This rule checks if a cryptographic key was generated by Rfc2898DeriveBytes with an iteration count that might be less than 100,000. A higher iteration count can help mitigate against dictionary attacks that try to guess the generated cryptographic key.
CA5389: Do not add archive item's path to the target file system path File path can be relative and can lead to file system access outside of the expected file system target path, leading to malicious config changes and remote code execution via lay-and-wait technique.
CA5390: Do not hard-code encryption key For a symmetric algorithm to be successful, the secret key must be known only to the sender and the receiver. When a key is hard-coded, it is easily discovered. Even with compiled binaries, it is easy for malicious users to extract it. Once the private key is compromised, the cipher text can be decrypted directly and is not protected anymore.
CA5391: Use antiforgery tokens in ASP.NET Core MVC controllers Handling a POST, PUT, PATCH, or DELETE request without validating an antiforgery token might be vulnerable to cross-site request forgery attacks. A cross-site request forgery attack can send malicious requests from an authenticated user to your ASP.NET Core MVC controller.
CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes By default, P/Invoke functions using DllImportAttribute probe a number of directories, including the current working directory for the library to load. This can be a security issue for certain applications, leading to DLL hijacking.
CA5393: Do not use unsafe DllImportSearchPath value There could be a malicious DLL in the default DLL search directories and assembly directories. Or, depending on where your application is run from, there could be a malicious DLL in the application's directory.
CA5394: Do not use insecure randomness Using a cryptographically weak pseudo-random number generator might allow an attacker to predict what security-sensitive value will be generated.
CA5395: Miss HttpVerb attribute for action methods All the action methods that create, edit, delete, or otherwise modify data needs to be protected with the antiforgery attribute from cross-site request forgery attacks. Performing a GET operation should be a safe operation that has no side effects and doesn't modify your persisted data.
CA5396: Set HttpOnly to true for HttpCookie As a defense in depth measure, ensure security sensitive HTTP cookies are marked as HttpOnly. This indicates web browsers should disallow scripts from accessing the cookies. Injected malicious scripts are a common way of stealing cookies.
CA5397: Do not use deprecated SslProtocols values Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Older protocol versions of TLS are less secure than TLS 1.2 and TLS 1.3 and are more likely to have new vulnerabilities. Avoid older protocol versions to minimize risk.
CA5398: Avoid hardcoded SslProtocols values Transport Layer Security (TLS) secures communication between computers, most commonly with Hypertext Transfer Protocol Secure (HTTPS). Protocol versions TLS 1.0 and TLS 1.1 are deprecated, while TLS 1.2 and TLS 1.3 are current. In the future, TLS 1.2 and TLS 1.3 might be deprecated. To ensure that your application remains secure, avoid hardcoding a protocol version.
CA5399: Definitely disable HttpClient certificate revocation list check A revoked certificate isn't trusted anymore. It could be used by attackers passing some malicious data or stealing sensitive data in HTTPS communication.
CA5400: Ensure HttpClient certificate revocation list check is not disabled A revoked certificate isn't trusted anymore. It could be used by attackers passing some malicious data or stealing sensitive data in HTTPS communication.
CA5401: Do not use CreateEncryptor with non-default IV Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks.
CA5402: Use CreateEncryptor with the default IV Symmetric encryption should always use a non-repeatable initialization vector to prevent dictionary attacks.
CA5403: Do not hard-code certificate The data or rawData parameter of a X509Certificate or X509Certificate2 constructor is hard-coded.
CA5404: Do not disable token validation checks TokenValidationParameters properties that control token validation should not be set to false.
CA5405: Do not always skip token validation in delegates The callback assigned to AudienceValidator or LifetimeValidator always returns true.
IL3000: Avoid accessing Assembly file path when publishing as a single file Avoid accessing Assembly file path when publishing as a single file.
IL3001: Avoid accessing Assembly file path when publishing as a single-file Avoid accessing Assembly file path when publishing as a single file.
IL3002: Avoid calling members annotated with 'RequiresAssemblyFilesAttribute' when publishing as a single file Avoid calling members annotated with 'RequiresAssemblyFilesAttribute' when publishing as a single file
IL3003: 'RequiresAssemblyFilesAttribute' annotations must match across all interface implementations or overrides. 'RequiresAssemblyFilesAttribute' annotations must match across all interface implementations or overrides.

Legend

The following table shows the type of information that is provided for each rule in the reference documentation.

Item Description
Type The TypeName for the rule.
Rule ID The unique identifier for the rule. RuleId and Category are used for in-source suppression of a warning.
Category The category of the rule, for example, security.
Fix is breaking or non-breaking Whether the fix for a violation of the rule is a breaking change. Breaking change means that an assembly that has a dependency on the target that caused the violation will not recompile with the new fixed version or might fail at run time because of the change. When multiple fixes are available and at least one fix is a breaking change and one fix is not, both 'Breaking' and 'Non-breaking' are specified.
Cause The specific managed code that causes the rule to generate a warning.
Description Discusses the issues that are behind the warning.
How to fix violations Explains how to change the source code to satisfy the rule and prevent it from generating a warning.
When to suppress warnings Describes when it is safe to suppress a warning from the rule.
Example code Examples that violate the rule and corrected examples that satisfy the rule.
Related rules Related rules.