Sunday 14 September 2014

Object.gethashcode in c#

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes.

 class Program
    {
        static void Main(string[] args)
        {
             B obj1 = new B();
            B obj2 = new B();
            Console.WriteLine(obj1==obj2);
            Console.WriteLine(obj1.Equals(obj2));
            Console.WriteLine(obj1.GetHashCode());
            Console.WriteLine(obj2.GetHashCode());
            Console.ReadLine();
        }
    }
    class B:Object
    {
        public override int GetHashCode()
        {
            return 1 ;
        }
        public override bool Equals(object obj)
        {
            return true;
        }
    }
Output:-
False
True
1
1

Here both object has same hashcode. It is not means that it is equal. but if it is two object are same then it has equal hashcode.

No comments:

Post a Comment