Right way to implement GetHashCode for this struct

In C# 7 you can do this:

public override int GetHashCode() => (Start, End).GetHashCode();

The ValueTuple is available in .NET Framework 4.7 and .NET Core, or via NuGet.

Not sure how well it performs, but I would be surprised if any custom code would beat it.


You can use the method from Effective Java as Jon Skeet shows here. For your specific type:

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        hash = hash * 23 + Start.GetHashCode();
        hash = hash * 23 + End.GetHashCode();
        return hash;
    }
}

I would trust Microsoft's implementation of GetHashCode() at the tuples and use something like this without any stupid magic:

public override int GetHashCode()
{
    Tuple.Create(x, y).GetHashCode();
}

Not to reanimate the dead, but I came here looking for something, and for newer C# versions you can do

public override int GetHashCode()
{
    return HashCode.Combine(Start, End);
}

The source can currently be found here: https://github.com/dotnet/corert/blob/master/src/System.Private.CoreLib/shared/System/HashCode.cs

In my preliminary tests (using Jon Skeets micro benchmarking framework) it appears to be very similar if not the same as the accepted answer, in terms of performance.

Tags:

C#

.Net

Hash