Override equals and operator equals on value types
TypeName |
OverrideEqualsAndOperatorEqualsOnValueTypes |
CheckId |
CA1815 |
Category |
Microsoft.Performance |
Breaking Change |
Non Breaking |
Cause
A public value type does not override 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 Suppress Warnings
It is safe to suppress a warning from this rule if instances of the value type will not be compared to each other.
Example of a Violation
Description
The following example shows a structure (value type) that violates this rule.
Code
using System;
namespace Samples
{
// Violates this rule
public struct Point
{
private readonly int _X;
private readonly int _Y;
public Point(int x, int y)
{
_X = x;
_Y = y;
}
public int X
{
get { return _X; }
}
public int Y
{
get { return _Y; }
}
}
}
Example of How to Fix
Description
The following example fixes the previous violation by overriding ValueTypeEquals and implementing the equality operators (==, !=).
Code
using System;
namespace Samples
{
public struct Point : IEquatable<Point>
{
private readonly int _X;
private readonly int _Y;
public Point(int x, int y)
{
_X = x;
_Y = y;
}
public int X
{
get { return _X; }
}
public int Y
{
get { return _Y; }
}
public override int GetHashCode()
{
return _X ^ _Y;
}
public override bool Equals(object obj)
{
if (!(obj is Point))
return false;
return Equals((Point)obj);
}
public bool Equals(Point other)
{
if (_X != other._X)
return false;
return _Y == other._Y;
}
public static bool operator ==(Point point1, Point point2)
{
return point1.Equals(point2);
}
public static bool operator !=(Point point1, Point point2)
{
return !point1.Equals(point2);
}
}
}
Related Rules
Override equals on overloading operator equals
Overload operator equals on overriding ValueType.Equals
Operators should have symmetrical overloads