What is the difference between GetHashCode implemented in the Object class and ValueType?

I summarized my question in the following code snippet

struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

    public void PrintValue()
    {
        Console.WriteLine(
            "{0},{1}",
            this.X, this.Y);
    }
}

the above struct is derived from ValueType, which contains the GetHashCode method. Below is the version of the class that is inferred from the object and contains a method GetHashCode.

class Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        this.X = x;
        this.Y = y;
    }

    public override int GetHashCode()
    {
        return base.GetHashCode();
    }

    public void PrintValue()
    {
        Console.WriteLine(
            "{0},{1}",
            this.X, this.Y);
    }
}

I just wanted to know. Is there any difference between these implementations?

+5
source share
1 answer

Yes; value-types ( structs) by default make their hash code as a composite value of their field values. You can observe this by trying:

var s = new Point(1,2); // struct
Console.WriteLine(s.GetHashCode());
s.X = 22; // <=============== struct fields should usually be readonly!
Console.WriteLine(s.GetHashCode()); // different

Please note that Equalsobeys the same rules.

(class) GetHashCode() Equals(). s.X = 22 class:

var s = new Point(1,2); // class
Console.WriteLine(s.GetHashCode());
s.X = 22;
Console.WriteLine(s.GetHashCode()); // same
+6

All Articles