skip to content

A C# method returns (decimal Net, decimal Tax); why does assigning it to (decimal Tax, decimal Net) silently swap the values?

level: middleimportance: should knowfreq 40%

answer

  1. names are aliases
  2. position decides, not name
  3. warning only on literals
  4. names inferred from variables

basics

~10 s

C# tuple element names are compile-time aliases for Item1 and Item2. Converting one tuple type to another matches elements by position, so the target's Tax receives the net amount, with no diagnostic.

solid answer

~50 s

Element names such as `Net` and `Tax` are aliases the compiler maps to `Item1` and `Item2`; the type underneath is plain `ValueTuple<decimal, decimal>`. Tuple types with the same number of elements convert **by position**, and names play no part, so `(decimal Tax, decimal Net) r = Calculate(120m);` compiles without even a warning, and `r.Tax` holds the net amount. The compiler warns (CS8123) only when a tuple **literal** spells a name that the target type does not use at that position, as in `(Tax: 20m, Net: 100m)` assigned to `(decimal Net, decimal Tax)`, and even then it assigns by position. Since C# 7.1 names are also **inferred** from variables and members, so `(net, tax)` gets elements `net` and `tax`. The fix is to let the declared names flow: use `var`, or deconstruct into variables you name in the right order.

code

csharp · 23 lines
csharp
using System;

var quote = Pricing.Calculate(120m);
Console.WriteLine($"Net={quote.Net} Tax={quote.Tax}");

(decimal Tax, decimal Net) reordered = Pricing.Calculate(120m); // no diagnostic
Console.WriteLine($"Net={reordered.Net} Tax={reordered.Tax}");   // values swapped

decimal net = 100m, tax = 20m;
var inferred = (net, tax);         // element names inferred from the variables (C# 7.1)
Console.WriteLine($"{inferred.tax} {inferred.Item2}");

(decimal Net, decimal Tax) literal = (Tax: 20m, Net: 100m);     // warning CS8123 twice
Console.WriteLine($"Net={literal.Net} Tax={literal.Tax}");

static class Pricing
{
    public static (decimal Net, decimal Tax) Calculate(decimal gross)
    {
        decimal net = Math.Round(gross / 1.2m, 2);
        return (net, gross - net);
    }
}

go deeper

for a junior

Recall that tuple element names are labels for Item1, Item2 and so on, and that var keeps the names a method declares.

for a middle

Explain that conversions match by position, that CS8123 fires only for names in a literal, and how C# 7.1 infers names from variables and members.

for a senior

Spot the same-type swap in review, where two decimals or two IDs convert silently in either order, and push for var, deliberate deconstruction or a named type.

for a principal

Weigh tuple convenience against the silent-swap risk when setting a team convention for multi-value returns of identically typed values.

## What a tuple element name is When a C# method is declared as returning `(decimal Net, decimal Tax)`, its real return type is `ValueTuple<decimal, decimal>`. The names `Net` and `Tax` are **aliases** the compiler keeps for that declaration and maps to the fields `Item1` and `Item2`. Writing `quote.Net` compiles to a read of `Item1`. `Item1` itself keeps working even when a name exists, and two tuple types that differ only in their names are the same type to the runtime. That one fact explains the swap: names help you read code, but they do not steer where values go. ## Conversions match by position C# allows assignment and conversion between tuple types when: - both have the **same number of elements**, and - each element on the right is the same type as, or implicitly convertible to, the element at the **same position** on the left. Names are not on that list. So this compiles with no warning and no error: ```csharp (decimal Tax, decimal Net) reordered = Pricing.Calculate(120m); // reordered.Tax == 100 (the net amount), reordered.Net == 20 ``` The value's first element was called `Net` in the method signature and is called `Tax` in the target, and the compiler assigns position 1 to position 1. Tuple `==` and `!=` ignore names in the same way. ## When the compiler does warn | Code | Diagnostic | Values assigned | |---|---|---| | Typed tuple to a differently named target | none | by position | | Literal `(Tax: 20m, Net: 100m)` to `(decimal Net, decimal Tax)` | warning CS8123 for each mismatched name | by position: `Net` = 20 | | Literal names compared with `==` against other names | warning CS8383 | compared by position | | An element named `Rest`, or `Item2` at position 1 | error CS8126 or CS8125 | does not compile | CS8123 reads: "The tuple element name 'Tax' is ignored because a different name or no name is specified by the target type '(decimal Net, decimal Tax)'." It fires only for names written **in a literal**, including a literal assigned to an unnamed target such as `(int, int)`. A whole tuple value flowing from a method, a variable or a field is converted with no check at all. ## Names the compiler infers Since C# 7.1, a tuple literal without explicit names takes them from its elements, a rule called *tuple projection initializers*: - `var t = (net, tax);` gets elements named `net` and `tax`. - `var p2 = (point.X, point.Y);` gets `X` and `Y` from the member names. - A candidate is skipped when it collides with a tuple member name such as `Item3`, `Rest` or `ToString`. - A candidate is skipped when it duplicates another element's name: `(net, net)` gets no names, and only `Item1` and `Item2` work. Inference is convenient, but it is another way for a name to appear that nobody typed, which makes position mismatches easier to miss in review. ## Names do not reach the run time Because the names are compile-time aliases, they are not stored in the `ValueTuple` value. The compiler records them in metadata on the declaring member so that other code compiled against it sees the names, but anything that inspects the value at run time sees only `Item1` and `Item2`. How that surfaces in serialization and `dynamic` code is a separate question. ## Defending against the swap 1. Let declared names flow: `var quote = Pricing.Calculate(120m);` keeps `Net` and `Tax` from the signature. 2. Deconstruct deliberately: `var (net, tax) = Pricing.Calculate(120m);` names the variables yourself, in the order you read from the declaration. 3. Do not restate a tuple type in a different order on the receiving side; the compiler will not catch it. 4. When two elements share a type and their order is easy to confuse, as two `decimal` amounts are, a small named type with `Net` and `Tax` properties removes the risk, because a property is found by name. The swap is a real bug class precisely because both elements have the same type: with `(string Name, int Age)` a reversed target would fail to compile, but two `decimal`s convert perfectly in either order.

  • Which tuple element names will the C# compiler refuse or not infer?
    Writing `Rest` as an element name is error CS8126 at any position, and `ItemN` is allowed only at position N (CS8125). Inference skips a candidate that matches a tuple member name such as `Item3`, `ToString` or `Rest`, and one that duplicates another element's name, so `(net, net)` has no names at all.
  • Can a C# override change the tuple element names of the member it overrides?
    No. Because names are part of the declaration's contract, an override that returns `(decimal Tax, decimal Net)` for a base member declared `(decimal Net, decimal Tax)` fails with CS8139, "cannot change tuple element names when overriding inherited member". The underlying types are identical; the compiler still protects the names here.
  • Do C# tuple element names affect tuple == comparisons?
    No. `==` and `!=` compare elements by position. If a literal on one side spells names that differ from the other side's, the compiler reports warning CS8383 but still compares position by position.

Two pairs of labelled jars on a shelf: tipping the left jar into the left jar and the right into the right moves the contents by position, whatever the labels say. Relabelling the target jars changes what you read, not what was poured.

  • Assigning a tuple to differently named elements matches them by name.
  • The compiler always warns when tuple element names fail to line up.
  • Once an element is named, Item1 no longer compiles.
  • Two tuple types with different element names are different runtime types.
  • Element names are stored inside every ValueTuple value.