How to override GetHashCode() method to get hash code for the current object in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    public class Point
    {
        private int x;
        private int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public override int GetHashCode()
        {
            return x ^ y;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Point pt = new Point(3, 7);
            Console.WriteLine(pt.GetHashCode());

            pt = new Point(7, 3);
            Console.WriteLine(pt.GetHashCode());
        }
    }
}


/*
run:
 
4
4

*/

 



answered Apr 24, 2016 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    public class Point
    {
        private int x;
        private int y;

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public override int GetHashCode()
        {
            return Tuple.Create(x, y).GetHashCode();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Point pt = new Point(3, 7);
            Console.WriteLine(pt.GetHashCode());

            pt = new Point(7, 3);
            Console.WriteLine(pt.GetHashCode());
        }
    }
}


/*
run:
 
100
228

*/

 



answered Apr 24, 2016 by avibootz

Related questions

2 answers 217 views
217 views asked Apr 25, 2017 by avibootz
1 answer 152 views
1 answer 151 views
151 views asked Aug 5, 2022 by avibootz
...