System.Collections.IStructuralEquatable
and System.Collections.IStructuralComparable
were added in .NET 4, but why aren't they generic, like IEquatable<T>
and IComparable<T>
?
Why aren't IStructuralEquatable and IStructuralComparable generic?
Because C# generics don't let you specify structural requirements for a type parameter. –
Duet
The example on MSDN gives part of the answer here; it seems to be useful for heterogeneous equality, rather than homogeneous equality - i.e. for testing whether two objects (/values) of potentially different types should be considered equal. In such scenarios, it is extremely likely that the calling code is dealing with object
(to represent heterogeneous data). And generic methods don't play nicely then.
However, all the
Tuple
classes simply return false
if the other object isn't exactly the same type. Array
seems to implement it correctly... –
Enzymology Array behaves the same as tuple for me. This test fails: Assert.IsTrue(StructuralComparisons.StructuralEqualityComparer.Equals(new[] { 5, 10 }, new[] { 5.0, 10.0 })); –
Moreland
There is no need for an equality operator that accepts different types. That should not even compile. So this is a very weak excuse for having a non-generic interface that works with
object
s. –
Continence I created a generic class which works fine:
var d = new Dictionary<int[], int>(new StructuralComparer<int[]>());
var arr1 = new int[] { 2, 3 };
var arr2 = new int[] { 2, 3 };
d.Add(arr1, 7);
Console.WriteLine(d[arr1]);
Console.WriteLine(d[arr2]); // would throw exception with structural comparison
class StructuralComparer<T> : IEqualityComparer<T>
{
public bool Equals(T? x, T? y) => StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
public int GetHashCode(T obj) => StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj);
}
© 2022 - 2025 — McMap. All rights reserved.