Surprising Tuple (in)equality

霸气de小男生 提交于 2019-12-03 22:11:12

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!