Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

HashCode.Combine — combining values into a hash code

HashCode.Combine produces an int hash code from one to eight values. It is useful in GetHashCode for types with field-based equality, but its result is neither a persistent identifier nor proof of equality.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

public static int Combine<T1, T2>(T1 value1, T2 value2);

HashCode.Combine is a static method on System.HashCode, available in .NET 10. Its overloads accept one to eight values and return an int. The displayed syntax covers two values; the compiler usually infers the type arguments. The single-argument overload improves the diffusion of a value's hash code.

In a GetHashCode implementation, include fields consistently with the rules of Equals. Equal objects must have equal hash codes; matching hash codes do not prove equality because collisions are possible. In the example, GridPoint compares X and Y, and HashCode.Combine(X, Y) uses those same fields in a fixed order.

Do not store the result as a persistent identifier or compare it across runs. HashCode uses a random seed for the process, and its implementation can change between versions. The example therefore prints comparison results rather than a numeric hash code.

For more than eight values, use a HashCode instance, successive calls to Add, and a final ToHashCode. Add also has an overload accepting a custom comparer, useful when hashing must match custom equality rules.

Examples

using System;

var first = new GridPoint(3, 7);
var second = new GridPoint(3, 7);

Console.WriteLine(first.Equals(second));
Console.WriteLine(first.GetHashCode() == second.GetHashCode());

readonly struct GridPoint
{
    public GridPoint(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; }
    public int Y { get; }

    public override bool Equals(object? obj) =>
        obj is GridPoint other && X == other.X && Y == other.Y;

    public override int GetHashCode() => HashCode.Combine(X, Y);
}

Result

True
True

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources