| title | ms.date | ms.topic | f1_keywords | helpviewer_keywords | ms.assetid | author | ms.author | manager | ms.workload | |||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CA1046: Do not overload operator equals on reference types |
11/04/2016 |
reference |
|
|
c1dfbfe3-63f9-4005-a81a-890427b77e79 |
mikejo5000 |
mikejo |
jillfra |
|
| Item | Value |
|---|---|
| CheckId | CA1046 |
| Category | Microsoft.Design |
| Breaking change | Breaking |
A public or nested public reference type overloads the equality operator.
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.
To fix a violation of this rule, remove the implementation of the equality operator.
It is safe to suppress a warning from this rule when the reference type behaves like a built-in value type. If it is meaningful to do addition or subtraction on instances of the type, it is probably correct to implement the equality operator and suppress the violation.
The following example demonstrates the default behavior when comparing two references.
[!code-csharpFxCop.Design.RefTypesNoEqualityOp#1]
The following application compares some references.
[!code-csharpFxCop.Design.TestRefTypesNoEqualityOp#1]
This example produces the following output:
a = new (2,2) and b = new (2,2) are equal? No
c and a are equal? Yes
b and a are == ? No
c and a are == ? YesIf you're running this rule from FxCop analyzers (and not with legacy analysis), you can configure which parts of your codebase to run this rule on, based on their accessibility. For example, to specify that the rule should run only against the non-public API surface, add the following key-value pair to an .editorconfig file in your project:
dotnet_code_quality.ca1046.api_surface = private, internalYou can configure this option for just this rule, for all rules, or for all rules in this category (Design). For more information, see Configure FxCop analyzers.
CA1013: Overload operator equals on overloading add and subtract
- xref:System.Object.Equals%2A?displayProperty=fullName
- Equality Operators