Alex Rivera | Logout

What problem does IStructuralEquatable and IStructuralComparable solve?

Asked 2010-08-31T14:09:45.363
73

I've noticed these two interfaces, and several associated classes, have been added in .NET 4. They seem a bit superfluous to me; I've read several blogs about them, but I still can't figure out what problem they solve that was tricky before .NET 4.

What use are IStructuralEquatable and IStructuralComparable?

Edit
Report

1 Answer

25

I had the same question. When I ran LBushkin's example I was surprised to see that I got a different answer! Even though that answer has 8 upvotes, it is wrong. After a lot of 'reflector'ing, here is my take on things.

Certain containers (arrays, tuples, anonymous types) support IStructuralComparable and IStructuralEquatable.

  • IStructuralComparable supports deep, default sorting.
  • IStructuralEquatable supports deep, default hashing.

{Note that EqualityComparer<T> supports shallow (only 1 container level), default hashing.}

As far as I see this is only exposed through the StructuralComparisons class. The only way I can figure out to make this useful is to make a StructuralEqualityComparer<T> helper class as follow:

    public class StructuralEqualityComparer<T> : IEqualityComparer<T>
    {
        public bool Equals(T x, T y)
        {
            return StructuralComparisons.StructuralEqualityComparer.Equals(x,y);
        }

        public int GetHashCode(T obj)
        {
            return StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj);
        }

        private static StructuralEqualityComparer<T> defaultComparer;
        public static StructuralEqualityComparer<T> Default
        {
            get
            {
                StructuralEqualityComparer<T> comparer = defaultComparer;
                if (comparer == null)
                {
                    comparer = new StructuralEqualityComparer<T>();
                    defaultComparer = comparer;
                }
                return comparer;
            }
        }
    }

Now we can make a HashSet with items having containers within containers within containers.

        var item1 = Tuple.Create(1, new int[][] { new int[] { 1, 2 }, new int[] { 3 } });
    
answered 2011-04-08T21:42:26.470

Your Answer