Skip to content

Latest commit

 

History

History
75 lines (55 loc) · 2.75 KB

File metadata and controls

75 lines (55 loc) · 2.75 KB
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
DoNotOverloadOperatorEqualsOnReferenceTypes
CA1046
CA1046
DoNotOverloadOperatorEqualsOnReferenceTypes
c1dfbfe3-63f9-4005-a81a-890427b77e79
mikejo5000
mikejo
jillfra
multiple

CA1046: Do not overload operator equals on reference types

Item Value
CheckId CA1046
Category Microsoft.Design
Breaking change Breaking

Cause

A public or nested public reference type overloads the equality operator.

Rule description

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.

How to fix violations

To fix a violation of this rule, remove the implementation of the equality operator.

When to suppress warnings

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.

Example

The following example demonstrates the default behavior when comparing two references.

[!code-csharpFxCop.Design.RefTypesNoEqualityOp#1]

Example

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 == ? Yes

Configurability

If 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, internal

You 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.

Related rules

CA1013: Overload operator equals on overloading add and subtract

See also