[API Proposal]: `HashCode.Combine(ReadOnlySpan<T>)`
- Dominant language
- C#
- Stars
- 18.3k
- Forks
- 5.6k
- PR merge metrics
- PR metrics pending
Description
### 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:
https://github.com/dotnet/runtime/blob/c458c40ffc0792b767bc529536388858313eed0a/src/coreclr/System.Private.CoreLib/src/System/Delegate.CoreCLR.cs#L232-L240
### API Proposal
```csharp
namespace System;
public struct HashCode
{
public static int Combine(params ReadOnlySpan values);
public int AddRange(ReadOnlySpan values);
public int AddRange(ReadOnlySpan values, IEqualityComparer? comparer);
}
```
### API Usage
```csharp
public readonly struct EquatableArray(T[] arr)
{
public T[] Values { get; } = arr;
// stuff
public bool Equals(EquatableArray other) => Values.SequenceEquals(other.Values);
public int GetHashCode() => HashCode.Combine(Values);
}
Dictionary, int> dict = new();
dict.Add(new([1, 2, 3]), 4);
```
### Alternative Designs
Use an instance and loop with adds.
### Risks
_No response_
Contributor guide
Research direction
Start by comparing the proposed HashCode APIs with the existing Combine and Add patterns, then read the referenced Delegate.CoreCLR.cs example. Check how variable-length spans and optional comparers should behave, including the EquatableArray usage shown. Done means the API design is resolved and supports the stated variable-element hashing scenario.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- csharp
- Domain
- api, backend-api-design
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Active
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100