Skip to content

[API Proposal]: HashCode.Combine(ReadOnlySpan<T>) #133410

Open

Description

@MichalPetryka

Background and motivation

Sometimes you need to compute hashcodes for variable amounts of elements or more than 8 of them (current Combine limit).

Having HashCode directly accept spans of values would greatly simplify such code.

BCL example:

if (TryGetInvocations(out ReadOnlySpan<Wrapper> invocations))
{
int hash = 0;
foreach (ref readonly Wrapper wrapper in invocations)
{
hash = hash * 33 + wrapper.GetHashCode();
}
return hash;
}

API Proposal

namespace System;

public struct HashCode
{
    public static int Combine<T>(params ReadOnlySpan<T> values);

    public int AddRange<T>(ReadOnlySpan<T> values);
    public int AddRange<T>(ReadOnlySpan<T> values, IEqualityComparer<T>? comparer);
}

API Usage

public readonly struct EquatableArray<T>(T[] arr)
{
    public T[] Values { get; } = arr;
    // stuff

    public bool Equals(EquatableArray<T> other) => Values.SequenceEquals(other.Values);
    public int GetHashCode() => HashCode.Combine(Values);
}

Dictionary<EquatableArray<int>, int> dict = new();
dict.Add(new([1, 2, 3]), 4);

Alternative Designs

Use an instance and loop with adds.

Risks

No response

Activity

  1. added
    api-suggestion
    on Sep 8, 2026
  2. added
    area-CodeGen-coreclr
    on Sep 8, 2026
  3. added
    untriaged
    on Sep 8, 2026
  4. dotnet-policy-service commented on Sep 8, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  5. added and removed
    area-CodeGen-coreclr
    on Sep 8, 2026
  6. dotnet-policy-service commented on Sep 8, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime
    See info in area-owners.md if you want to be subscribed.

  7. tannergooding commented on Sep 8, 2026

    @tannergooding
    Member

    Having HashCode directly accept spans of values would greatly simplify such code.

    Calling it a "great" simplification is a bit of a stretch. You're removing what is 3-6 lines for a one liner, that is removing a for loop for something which does a for loop. There's also nuances in that Add/Combine will do more work than what you've referenced which may or may not be acceptable depending on the scenario.

    Given that this is just a one liner for a for loop, I'd normally close this as not something we're interested in provided. That being said, there is some minor benefit here in that we can make the main loop avoid the redundant checking of whether position is 0, 1, 2, or 3 every iteration and provide some marginal perf speed up instead so it "might" be worth keeping open.

    -- The alternative, which would still provide such a speedup, is to expose Add overloads which mirror the Combine overloads allowing the same optimizations to be manually implemented.

  8. hamarb123 commented on Sep 8, 2026

    @hamarb123
    Contributor
    int hash = 0; 
    foreach (ref readonly Wrapper wrapper in invocations) 
    { 
       hash = hash * 33 + wrapper.GetHashCode(); 
    } 
    return hash;

    this would not be an appropriate general implementation imo; consider I had something like this:

    class MyClass
    {
        int[] field1;
        int[] field2;
    
        public int GetHashCode()
        {
            HashCode hc = new();
            hc.AddRange(field1);
            hc.AddRange(field2);
            return hc.ToHashCode();
        }
    }

    now you cannot distinguish between field1 = [], field2 = [1] and field1 = [1], field2 = [] - they would get the same hashcode.

    For this reason, I always include the length in the hashcode first, and then all of the items - this makes the collision harder in my experience (ofc it's still possible, but not so trivially on accident by just moving elements from one field to another in the same order).

    Personally, I just write this as an extension in the stuff where I need it.

  9. removed
    untriaged
    on Sep 9, 2026
  10. added this to the Future milestone on Sep 9, 2026
  11. jeffhandley commented on Sep 9, 2026

    @jeffhandley
    Member

    @MichalPetryka, please update the proposal to focus on the HashCode.Add overloads suggested by @tannergooding, including the intended performance rationale and semantic considerations discussed above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions