thecoop
thecoop

Reputation: 46148

Why aren't IStructuralEquatable and IStructuralComparable generic?

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

Upvotes: 13

Views: 1888

Answers (2)

citykid
citykid

Reputation: 11122

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);
}

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063874

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.

Upvotes: 3

Related Questions