Override GetHashCode on overriding Equals

TypeName

OverrideGetHashCodeOnOverridingEquals

CheckId

CA2218

Category

Microsoft.Usage

Breaking Change

NonBreaking

Cause

A public type overrides System.Object.Equals but does not override System.Object.GetHashCode.

Rule Description

GetHashCode returns a value based on the current instance that is suited for hashing algorithms and data structures such as a hash table. Two objects that are the same type and are equal must return the same hash code to ensure that instances of System.Collections.HashTable and System.Collections.Generic.Dictionary<TKey, TValue> work correctly.

How to Fix Violations

To fix a violation of this rule, provide an implementation of GetHashCode. For a pair of objects of the same type, you must ensure that the implementation returns the same value if your implementation of Equals returns true for the pair.

When to Exclude Warnings

Do not exclude a warning from this rule.

Example

The following example shows a type that violates this rule.

using System;

namespace UsageLibrary
{
    public struct PointWithoutHash
    {
        private int x,y;
        
        public PointWithoutHash(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        
        public override string ToString()
        {
            return String.Format("({0},{1})",x,y);
        }
        
        public int X {get {return x;}}
        
        public int Y {get {return x;}}
        
        // Violates rule: OverrideGetHashCodeOnOverridingEquals.
        // Violates rule: OverrideOperatorEqualsOnOverridingValueTypeEquals.
        public override bool Equals (object obj)
        {
            if (obj.GetType() != typeof(PointWithoutHash))
                return false;
                
            PointWithoutHash p = (PointWithoutHash)obj;   
            return ((this.x == p.x) && (this.y == p.y));
        }
        
    }

}

The following example shows a structure (value type) that violates this rule.

The following example fixes the above violation by overriding ValueType.GetHashCode.

The following example shows a class (reference type) that violates this rule.

The following example fixes the above violation by overriding Object.GetHashCode.

Do not overload operator equals on reference types

Operator overloads have named alternates

Operators should have symmetrical overloads

Override equals on overloading operator equals

Overload operator equals on overriding value type equals

See Also

Reference

Guidelines for Implementing Equals and the Equality Operator (==)
System.Object.Equals
System.Object.GetHashCode
System.Collections.HashTable