9

Given two variables of type (int, int), how do I check if they represent equal values?

For example:

var a = (1, 2);
var b = (1, 2);

var c = a == b; // Error CS0019 Operator '==' cannot be applied to operands
                // of type '(int, int)' and '(int, int)'

How is this comparison meant to be done in C# 7? Should I use .Equals instead or do it some other way?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
Ivan
  • 63,011
  • 101
  • 250
  • 382

1 Answers1

17

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
David Arno
  • 42,717
  • 16
  • 86
  • 131
  • Note that if a is Nullable and c is T then even if a.Equals(c) and b.Equals(d), (a, b).Equals((c, d)) still returns false. – duongntbk Jun 03 '21 at 10:34