Let's consider the following naive implementation to check whether a type has a proper EqualityComparer<T>.Default implementation for HashSet:
bool IsHashEqual<T>(Func<T> f) where T : struct, IEquatable<T>
{
var set = new HashSet<T>();
set.Add(f());
set.Add(f());
return set.Count == 1;
}
We can verify the following:
Assert.True(IsHashEqual(() => 42));
Assert.True(IsHashEqual(() => 3.14));
Assert.True(IsHashEqual(() => true));
With a bit of work, we can extend the above IsHashEqual code and verify this property also on the string class.
However we can make the above code fails with something like:
Assert.False(IsHashEqual(() => ImmutableArray.Create(new byte[] { 0, 1, 2, 3 })));
How can I rework my generic constraints so that it matches the expectation of the default equality comparer (EqualityComparer<T>.Default) ? Or else can I infer from type T that I need to use StructuralComparisons.StructuralEqualityComparer ?
References: