I have summarized my question in 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);
}
}
above struct is derived from ValueType which contains GetHashCode method. Below is a class version which derives from Object and contains GetHashCode method.
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?
Yes; value-types (
structs) by default make their hash-code as a composite of the values of their fields. You can observe this by trying:Note that
Equalsobeys similar rules.By contrast, a reference-type (
class) uses, by default, the reference itself for bothGetHashCode()andEquals(). Thes.X = 22will not impact aclass: