Share via


Override equals and operator equals on value types

TypeName

OverrideEqualsAndOperatorEqualsOnValueTypes

CheckId

CA1815

Category

Microsoft.Performance

Breaking Change

NonBreaking

Cause

A public value type does not override System.Object.Equals, or does not implement the equality operator (==). This rule does not check enumerations.

Rule Description

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 use them as hash table keys, your value type should implement Equals. If your programming language supports operator overloading, you should also provide an implementation of the equality and inequality operators.

How to Fix Violations

To fix a violation of this rule, provide an implementation of Equals. If you can, implement the equality operator.

When to Exclude Warnings

It is safe to exclude a warning from this rule if instances of the value type will not be compared to each other.

Override equals on overloading operator equals

Overload operator equals on overriding value type equals

Operators should have symmetrical overloads

See Also

Reference

System.Object.Equals