Overriding GetHashCode , Equals methods.


While browsing through questions  of C# , 
I came across this question

If A.equals(B) is true then A.getHashcode & B.getHashCode must always return same hash code

I found this interesting example in the site 
--https://vkreynin.wordpress.com/2008/07/05/explaining-gethashcode-method/
Which explains this questions .
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. 
 
 
using System;

public class Point
{
        private readonly int _x;
        private readonly int _y;

        public Point(int x,int y)
        {
                _x=x;
                _y=y;

        }
        public override bool Equals(object obj)
        {
                //if(((Point)obj)._x==_x && ((Point)obj)._y==_y)
                //return true;
                //else
                //return false;

                if(ReferenceEquals(this ,obj)) return true;
                return ((Point)obj)._x==_x && ((Point)obj)._y==_y;

        }

        public override int GetHashCode()
        {
         unchecked
                {
                        return (_x*397)^_y;
                }
        }


}
public class Program
{
        public static void Main()
        {

        Point point_1= new Point(2,3);
        Point point_2= new Point(2,3);

        Console.WriteLine("Point_1 HashValue :{0}",point_1.GetHashCode());
        Console.WriteLine("Point_2 HashValue :{0}",point_2.GetHashCode());
        Console.WriteLine("Point_1 is equal to Point2 {0}",point_1.Equals(point_2));
        //Hashtable hashtable = new Hashtable();
        //hashtable.Add(new Point(2,3),"Point1");
        //hashtable.Add(new Point(5,3),"Point2");
        //hashtable.Add(new Point(2,3),"Point3");
        }

}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6