Prior to C# 7.3, you had two choices: use .Equals
, or you can write out the ==
comparison long-hand, for elements that themselves support ==
:
(a, b).Equals((c, d)) // true if a.Equals(c) && b.Equals(d)
a == c && b == d // works if the types support ==
(For details of how Equals()
works, check out the source.)
As of C# 7.3, direct support for ==
has been added to value tuples:
(a, b) == (c, d) // compiler converts to a == c && b == d
Note that ==
here is not an operator defined by the tuple types. It's a "compiler trick" that recursively (for nested tuples) performs ==
on each of the elements. As a result, this technique can only be used if the elements support ==
themselves. As a result, this approach does not work for generics, unless constrained to types that do support ==
. So the following code will not compile:
public bool Compare<T1, T2>((T1 a, T2 b) x, (T1 a, T2 b) y) => x == y