How to compare Tuples?

A few days back I was asked, How to compare tuples? This is currently a easy task to accomplish thanks to C# 7.3. On that release, support for the == and the != operator was added.

The operators work by comparing each member of the left to each member of the right. The comparisons will short-circuit, they will stop evaluating as soon as one pair is not equal, similar to a && evaluation. Once can perform a implicit conversion on each member of both tuples. let’s say int and long. Let’s see it in action.

var leftTuple = (a: 5, b: 10);
var rightTuple = (a: 5, b: 10);
Console.WriteLine(leftTuple == rightTuple); // displays 'true'

// lifted conversions
var left = (a: 5, b: 10);
(int? a, int? b) nullableMembers = (5, 10);
Console.WriteLine(left == nullableMembers); // Also true

// converted type of left is (long, long)
(long a, long b) longTuple = (5, 10);
Console.WriteLine(left == longTuple); // Also true

// comparisons performed on (long, long) tuples
(long a, int b) longFirst = (5, 10);
(int a, long b) longSecond = (5, 10);
Console.WriteLine(longFirst == longSecond); // Also true

A cool thing is that tuple member’s names do not participate in the equality operation. Check it out!

(int a, string b) pair = (1, "Hello");
(int z, string y) another = (1, "Hello");
Console.WriteLine(pair == another); // true. Member names don't participate.
Console.WriteLine(pair == (z: 1, y: "Hello")); // warning: literal contains different member names

Now you know, Comparing tuples is easy to do. either for a unit test purpose or in your code.

Spread the word
  • Yum