skip to content

In C#, how does == compare two value tuples, and when can it disagree with ValueTuple.Equals?

level: middleimportance: should knowfreq 45%

answer

  1. no operator on the type
  2. the compiler expands it
  3. each element's own ==
  4. NaN and object elements
  5. all operands evaluated first

basics

~10 s

Since C# 7.3 the compiler rewrites tuple == into element-by-element == comparisons, ignoring names. Equals uses EqualityComparer<T>.Default per element instead, so NaN or object-typed elements can make the two disagree.

solid answer

~40 s

`ValueTuple` declares no `operator ==`. Since C# 7.3 the compiler rewrites `t1 == t2` into `t1.Item1 == t2.Item1 && t1.Item2 == t2.Item2`, after evaluating both operands. It needs the same number of elements on both sides (otherwise error CS8384), converts each pair as needed, ignores element names, stops comparing at the first unequal pair, and also works on nullable tuples. Each pair uses that element type's own `==`, so `double.NaN == double.NaN` is false and `==` on `object` elements compares references. `ValueTuple.Equals` instead calls `EqualityComparer<T>.Default.Equals` per element, which treats NaN as equal to NaN and calls an overridden `Equals`. So `(double.NaN, 1) == (double.NaN, 1)` is false while `Equals` returns true, and a `HashSet` or `Dictionary` key follows `Equals`, not `==`.

code

csharp · 20 lines
csharp
using System;

(decimal Net, decimal Tax) a = (100m, 20m);
(decimal Tax, decimal Net) b = (100m, 20m);
Console.WriteLine(a == b);                    // True: positions compared, names ignored
Console.WriteLine((100, 20m) == (100m, 20));  // True: each pair converted, then compared

var reading = (double.NaN, 1);
var again = reading;
Console.WriteLine(reading == again);          // False: double's == treats NaN as unequal
Console.WriteLine(reading.Equals(again));     // True: EqualityComparer<double>.Default

(object, int) left = (new string('x', 3), 1);
(object, int) right = ("xxx", 1);
Console.WriteLine(left == right);             // False: == on object compares references
Console.WriteLine(left.Equals(right));        // True: Equals reaches string.Equals

Console.WriteLine((Log("L1"), Log("L2")) == (Log("R1"), Log("R2")));

static int Log(string s) { Console.Write(s + " "); return s == "L1" ? 0 : 1; }

go deeper

for a junior

Recall that two value tuples compare with == element by element, ignoring the element names.

for a middle

Explain the C# 7.3 rewrite: both operands evaluated, each pair compared with its own ==, results chained with && or ||, and CS8384 for mismatched lengths.

for a senior

Diagnose disagreements between == and Equals from NaN or object-typed elements, and explain why dictionary lookups follow Equals.

for a principal

Decide whether tuple keys with floating-point or reference-typed elements are acceptable in shared code, or whether a named type with explicit equality should own that rule.

## Tuple `==` is a compiler feature, not an operator Neither `ValueTuple<T1, T2>` nor any other `ValueTuple` type declares `operator ==`. Before C# 7.3, `t1 == t2` on two value tuples did not compile. C# 7.3 added **tuple equality**: when both operands of `==` or `!=` are tuples (tuple-typed values or tuple literals) with the same number of elements, the compiler expands the comparison into one comparison per element. Nothing at run time knows about it, which is why it is worth knowing exactly what the expansion does. ## How the expansion works The C# 7.3 design describes the order precisely, and the compiler in the .NET 10 SDK behaves that way: 1. The left operand is evaluated, then the right operand. For tuple literals, their elements are evaluated left to right. **All** of them run before any comparison. 2. Each pair of elements is compared with that pair's own `==` (or `!=`), recursively for nested tuples, with any conversion the pair needs. 3. The results are chained with `&&` for `==` and `||` for `!=`, so comparison stops at the first pair that decides the answer. In `(Log("L1"), Log("L2")) == (Log("R1"), Log("R2"))`, all four calls run and print before the result, even when the first pair already differs. Only the comparisons short-circuit, not the evaluation of operands. Further rules: - **Cardinality must match.** `(1, 2) == (1, 2, 3)` is error CS8384, not a run-time `false`. - **Each pair must be comparable.** `(100, 20m) == (100m, 20)` compiles and is `true`, because `int` converts to `decimal` in each pair; `(1, (2, 3)) == ((1, 2), 3)` does not compile. - **Names are ignored.** `(decimal Net, decimal Tax)` equals `(decimal Tax, decimal Net)` when the values match by position. A literal whose names differ from the other side's triggers warning CS8383, and the comparison is still positional. - **Nullable tuples work.** `(int, int)? maybe = null;` makes `maybe == (1, 2)` evaluate to `false` with no exception. ## Where `==` and `Equals` part ways `ValueTuple<T1, T2>.Equals(ValueTuple<T1, T2>)` is a library method. Its source compares `EqualityComparer<T1>.Default.Equals(Item1, other.Item1)` and then the second pair. The two mechanisms therefore agree only when each element type's `==` agrees with its default equality comparer. | Element type | `==` per element | `Equals` per element | Can they differ? | |---|---|---|---| | `int`, `decimal`, `bool` | value comparison | value comparison | no | | `double` holding `NaN` | `NaN == NaN` is `false` | `double.Equals` treats `NaN` as equal | yes | | `string` | value comparison through `string`'s `==` | value comparison | no | | `object` holding equal strings | reference comparison | virtual `Equals`, so text comparison | yes | | class overriding `Equals` without `==` | reference comparison | the override | yes | The `double` row comes straight from the runtime: `double.Equals(double)` returns `true` when both values are NaN, while the `==` operator follows IEEE 754 and never treats NaN as equal. The `object` row is the general rule that `==` on a reference type without its own overload checks identity; the lesson on equality and hashing covers that contract in depth. ## Practical consequences - **Collections use `Equals`.** A value tuple used as a `Dictionary` key or `HashSet` element is matched through `EqualityComparer<T>.Default`, so a NaN element still finds its entry even though `==` says the tuples differ. - **Generic code cannot use tuple `==`.** In `static bool Same<T>(T x, T y) => x == y;` the compiler reports CS0019, because the element-wise rewrite needs tuple types it can see. Use `EqualityComparer<T>.Default.Equals(x, y)` instead. - **Side effects in operands always run.** Do not write `(Load(a), Load(b)) == expected` expecting the second load to be skipped. - **Declared element types matter.** Typing elements as `object` silently turns `==` into a reference comparison for every element, while `Equals` keeps comparing values. ## Checking a claim quickly When a review comment says two tuples "should be equal", check three things in order: 1. Do both sides have the same number of elements, nested the same way? If not, the code does not compile. 2. What is the **declared** type of each element? `==` follows the declared type, so an `object` or interface element compares references. 3. Is the comparison written with `==`, or does it go through `Equals`, a hashed collection or `EqualityComparer<T>.Default` in generic code? Those three all end in each element's default equality comparer. The rule to remember: tuple `==` asks each element's `==`; tuple `Equals` asks each element's default equality comparer. Most of the time they agree, and an interview probes the cases where they do not.

  • Why does `static bool Same<T>(T x, T y) => x == y;` not let you compare two tuples in C#?
    The body fails with CS0019 because `==` is not defined for an unconstrained `T`, and tuple equality is a compile-time rewrite that needs tuple types the compiler can see. In generic code use `EqualityComparer<T>.Default.Equals(x, y)`, which for a value tuple calls `ValueTuple.Equals`.
  • Does `(F(), G()) == (H(), K())` in C# call all four methods when F() and H() return different values?
    Yes. Both operands are evaluated completely, left to right, before any element comparison. Only the element comparisons short-circuit, so after the first pair differs the second pair is not compared, but G() and K() have already run.
  • Can C# compare tuples whose element types differ?
    Yes, when each pair is comparable with `==`, using implicit conversions per position: `(100, 20m) == (100m, 20)` is true. Structure must match, so `(1, (2, 3)) == ((1, 2), 3)` does not compile, and different element counts give CS8384.

  • ValueTuple overloads operator == to call Equals.
  • Tuple == compares element names as well as values.
  • Tuple == and ValueTuple.Equals always give the same answer.
  • Tuples of different lengths are simply unequal at run time.
  • Tuple == skips evaluating later operands once an element differs.