Why aren't IStructuralEquatable and IStructuralComparable generic?
Asked Answered
E

2

12

System.Collections.IStructuralEquatable and System.Collections.IStructuralComparable were added in .NET 4, but why aren't they generic, like IEquatable<T> and IComparable<T>?

Enzymology answered 11/2, 2011 at 11:41 Comment(1)
Because C# generics don't let you specify structural requirements for a type parameter.Duet
B
3

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.

Bolling answered 11/2, 2011 at 11:49 Comment(3)
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 objects.Continence
D
0

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);
}
Daph answered 10/11, 2023 at 8:21 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.