1

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.

Community
  • 1
  • 1
Pavel Ronin
  • 549
  • 4
  • 9
  • Note that the `==` operator is entirely separate from the `Equals` method... whereas `Equals` and `GetHashCode` need to be aligned. – Jon Skeet Feb 02 '16 at 10:53
  • MSDN is vague in one particular area, but it still provides enough information for you to answer *most* of your questions, such as what `==` will do. – Jon Skeet Feb 02 '16 at 11:00
  • @Grant Winney many thanks. The part that confuses me is EqualityComparer.Default. Will it work for all cases, assuming that the Items of the tuple are not custom classes? – Pavel Ronin Feb 02 '16 at 11:00
  • What do you mean by "custom classes"? Basically, `EqualityComparer.Default` will call the regular `Equals(object)` code... so it's up to how the relevant classes override that. – Jon Skeet Feb 02 '16 at 11:08
  • Got a bit confused by the implementation. I understand it now. Thanks. – Pavel Ronin Feb 02 '16 at 11:17

1 Answers1

3

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
Jon Skeet
  • 1,261,211
  • 792
  • 8,724
  • 8,929