Search code examples
c#tuplesdesign-decisions

Tuples implementation


Sorry if it's a duplicate. I couldn't find a full explanation on that matter. And the MSDN is vague as usual...

Does the .Net tuples provide a usable implementation for equals and GetHashCode out of the box? (And consequently the == operator)

Can I expect a tuple to compare all it's item by default or must I provide an IEqualityComparer as is shown here net-tuple-and-equals-performance?

Can it be reliably applied as dictionary keys?

I've ran a small test :

Tuple<DateTime, string, int> test3 = new Tuple<DateTime, string, int>(DateTime.Now.Date, "1", 1);
Tuple<DateTime, string, int> test4 = new Tuple<DateTime, string, int>(DateTime.Now.Date, "1", 1);

Console.WriteLine(test3 == test4);
Console.WriteLine(test3.Equals(test4));

Console.ReadKey();

The result was false and true. I guess the equals is implemented but not the operator. Does this mean that the == operator compares references? Also, I couldn't find the overload with the IEqualityComparer(framework version 4).

Thanks.


Solution

  • Looking at the documentation, you can see that:

    • GetHashCode is overridden, although the details are not clearly documented. (It could return 0 for all instances, for example.)
    • Equals is overridden in a well-documented way, delegating to the equality comparer of the component types.
    • The == operator is not overloaded - so yes, it will have perform regular reference-identity comparison

    Although it's not clearly documented, the compile-time component types have to be equal, not just the execution-time component types. So for example:

    var t1 = new Tuple<object, object>("foo", "bar");
    var t2 = new Tuple<string, string>("foo", "bar");
    Console.WriteLine(t1.Equals(t2)); // False