Override equals and operator equals on value types
| TypeName | OverrideEqualsAndOperatorEqualsOnValueTypes |
| CheckId | CA1815 |
| Category | Microsoft.Performance |
| Breaking Change | NonBreaking |
A public value type does not override System.Object.Equals, or does not implement the equality operator (==). This rule does not check enumerations.
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.
Seems that if one defines a struct and if you encounter this rule, you will afterwards also encounter a compiler warning stating:
Warning 1 'xxx' overrides Object.Equals(object o) but does not override Object.GetHashCode
Warning 2 'xxx' defines operator == or operator != but does not override Object.GetHashCode
The following example shows a structure (value type) that violates this rule.
[C#]
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; }
}
}
}
The following example fixes the above violation by overriding ValueType.Equals and implementing the equality operators (==, !=).
[C#]
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);
}
}
}
- 10/29/2006
- David M. Kean
- 12/12/2007
- rlarno