开发者

Surprising Tuple (in)equality

开发者 https://www.devze.com 2023-02-12 04:44 出处:网络
Until today, my understanding of .NET Tuple classes had been that they delegate their implementation of Equals() to their contents, allowing me to equate and compare them \"by value\".

Until today, my understanding of .NET Tuple classes had been that they delegate their implementation of Equals() to their contents, allowing me to equate and compare them "by value".

Then this test came along and made a fool out of me:

[TestMethod]
public void EquateTwoTuplesWithSameContent()
{
    var t1 = Tuple.Create("S");
    var t2 = Tuple.Create((object)t1.Item1);
    Assert.IsTrue(t1.Equals(t2)); // Boom!
}

Reading through MSDN documentation and various blogs has left me with more questions. From what I gather, it would seem that Tuple<object> and Tuple<TWhatever> are always considered not equal, regardless of the fact t开发者_如何学编程hat both instances may wrap the same object (boxed or typecast - it's all the same).

Is this really how Tuples are supposed to behave? Is structural compatibility actually an additional constraint on equality as opposed to a relaxation, as I've been interpreting it until now?

If so, is there anything else in the BCL that I can use to meet the expectations of the above unit test?

Thank you in advance!


Tuples require the following to be true for the objects to be considered "equal":

  • Must be a Tuple object with the same number of generic parameter(s) as the current object.
  • Each of those generic parameters must be of the same type as the other.
  • Each member of the tuple must have the same value as the corresponding member of the other.

So, because a Tuple<object> has a different generic parameter than a Tuple<string>, they are not equal even if the object is actually a reference to a string of the same value as the strongly-typed Tuple<string>.


Yes, I'd say that's how tuples are supposed to behave. You've got two different tuple types here - Tuple<string> and Tuple<object>.

The documentation for Tuple<T1>.Equals states that two of the conditions are:

  • It is a Tuple<T1> object.
  • Its single component is of the same type as the current instance.

That's not true if you ask whether a Tuple<string> is equal to a Tuple<object>, so it returns false.

In general I think it's a very bad idea for instances of two different types to be deemed equal to each other. It invites all kinds of issues.


Is this really how Tuples are supposed to behave? Is structural compatibility actually an additional constraint on equality as opposed to a relaxation, as I've been interpreting it until now?

Tuple<T1> implements IStructuralEquatable - which, by its name, does exactly that - checks the structure as well as the contents.

You could always rework your Unit test to check the Item contents of the tuple for equality, instead of the Tuple itself.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号