Export (0) Print
Expand All
Expand Minimize

Override GetHashCode on overriding Equals

TypeName

OverrideGetHashCodeOnOverridingEquals

CheckId

CA2218

Category

Microsoft.Usage

Breaking Change

NonBreaking

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

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.

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.

Do not exclude a warning from this rule.

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.

Community Additions

ADD
Show:
© 2014 Microsoft