skip to content

A C# pricing service returns (decimal Net, decimal Tax), yet System.Text.Json serializes the result as {}; why, and what is the fix?

level: seniorimportance: nice to knowfreq 30%

answer

  1. names exist only for the compiler
  2. ValueTuple's members are fields
  3. an attribute on the signature
  4. a named type at the boundary

basics

~20 s

A C# tuple is a ValueTuple whose elements are fields named Item1 and Item2, and System.Text.Json skips fields by default. Net and Tax exist only in compiler metadata, so return a named record or class instead.

solid answer

~40 s

At run time the value is a plain `ValueTuple<decimal, decimal>`: its elements are **public fields** named `Item1` and `Item2`, and the names `Net` and `Tax` are not part of the type. The compiler records them in a `TupleElementNamesAttribute` on the method's return value, which other C# code compiled against the method reads, but which the value itself does not carry. System.Text.Json serializes public properties and skips fields unless `IncludeFields` is set, so the tuple becomes `{}`; with `IncludeFields` you get `{"Item1":100,"Item2":20}`, which is no better. `dynamic` access to `Net` throws `RuntimeBinderException` for the same reason. The fix is a named type at the boundary, such as `record PriceQuote(decimal Net, decimal Tax)`, whose properties carry their names into the JSON. Keep tuples for private and internal plumbing, where the compiler can see the names.

code

csharp · 28 lines
csharp
#:property PublishAot=false
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;

var quote = Pricing.Calculate(120m);
Console.WriteLine(JsonSerializer.Serialize(quote));       // {}
Console.WriteLine(string.Join(",", quote.GetType().GetFields().Select(f => f.Name)));
Console.WriteLine(quote.GetType());

var names = typeof(Pricing).GetMethod(nameof(Pricing.Calculate))!
    .ReturnParameter.GetCustomAttribute<TupleElementNamesAttribute>()!.TransformNames;
Console.WriteLine(string.Join(",", names));               // the names live on the method

Console.WriteLine(JsonSerializer.Serialize(new PriceQuote(quote.Net, quote.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);
    }
}

public record PriceQuote(decimal Net, decimal Tax);

go deeper

for a junior

Recall that tuple element names are for the compiler only; at run time the elements are the fields Item1 and Item2.

for a middle

Explain that the compiler stores names in a TupleElementNamesAttribute on the declaration, and why object, dynamic and reflection never see them.

for a senior

Diagnose the empty or Item1-shaped JSON quickly, replace the tuple with a named type at the boundary, and catch the same flaw in logging and dynamic code.

for a principal

Draw the team line between tuples for internal plumbing and named types for anything stored, serialized or exposed, and say what the extra declarations buy.

## The symptom A pricing service computes a net amount and a tax amount and returns them as `(decimal Net, decimal Tax)`. Inside the service everything reads well: callers write `quote.Net` and `quote.Tax`. Then the same value is handed to `JsonSerializer.Serialize`, and the output is `{}`. Nothing threw, the values were computed correctly, and the payload is empty. The cause lies in what a C# tuple is at run time. ## What exists at run time - The value's type is `System.ValueTuple<decimal, decimal>`; `quote.GetType()` prints ``System.ValueTuple`2[System.Decimal,System.Decimal]``. - Its members are **public fields**, `Item1` and `Item2`, as declared in the runtime source of `ValueTuple<T1, T2>`. There are no properties holding the elements. - The names `Net` and `Tax` are **not** stored in the value. Microsoft's tuple reference states that the compiler replaces non-default field names with the default names, so they "aren't available at run time". ## Where the names actually live When a member's signature contains named tuple elements, the compiler emits a `System.Runtime.CompilerServices.TupleElementNamesAttribute` on it. For `Calculate`, reflection over the method's return parameter finds the attribute with `TransformNames` equal to `Net, Tax`. That is how another project that references the assembly still sees `quote.Net` in its code: its compiler reads the attribute. The names are therefore attached to **declarations**, not to values. Anything that only sees the value loses them: 1. Code that receives the tuple as `object` or as a generic `T`. 2. `dynamic`: `dynamic d = quote; d.Net` throws `Microsoft.CSharp.RuntimeBinder.RuntimeBinderException`, because the binder inspects `ValueTuple<decimal, decimal>`, which has no member called `Net`. 3. Serializers, loggers and mappers that inspect the value with reflection. ## Why the serializer writes `{}` System.Text.Json's default contract includes public properties and leaves out public fields; turning on `JsonSerializerOptions.IncludeFields` changes that, and the serializer's configuration in general is covered in the material on the base class library. A value tuple has no properties at all, so the default output is an empty object. Turning fields on does not restore the names either: the output becomes `{"Item1":100,"Item2":20}`, because `Item1` and `Item2` are the only names that exist at run time. A client that looks for a `net` or `Net` member finds nothing in either output. ## The fix: a named type at the boundary Declare the shape the outside world sees: ```csharp public record PriceQuote(decimal Net, decimal Tax); ``` A positional record generates `Net` and `Tax` as public properties, so the serializer writes `{"Net":100,"Tax":20}`; a class or struct with properties works the same way. How records generate those members is covered with records. Choosing a return shape for several values comes up often, and the trade-offs are concrete: | | Value tuple | `out` parameters | Named class, struct or record | |---|---|---|---| | Names visible at run time | no | not applicable | yes | | Usable from `async` methods | yes, as `Task<(decimal, decimal)>` | no, error CS1988 | yes | | Works with deconstruction | built in | not applicable | through `Deconstruct` | | Cost to introduce | none | none | one type declaration | | Typical home | private and internal helpers | `Try...` methods | public APIs, wire formats, logs | ## A rule a reviewer can apply - Keep value tuples for values consumed **immediately** by C# code that sees the declaration: private helpers, LINQ intermediates, deconstruction at the call site. - Introduce a named type the moment the value **crosses a boundary**: a public API, a serializer, a log event, a message queue, or `dynamic` code. - A C# 12 `using` alias such as `using PriceQuote = (decimal Net, decimal Tax);` is not that fix: an alias introduces no new type, so the serializer still sees `ValueTuple<decimal, decimal>`. ## Spotting it in review - A method whose return type is a named tuple and whose result reaches `JsonSerializer`, a logger's structured payload or an HTTP response is the pattern to flag. - `object`-typed or generic plumbing between the method and the consumer is a hint that the names are already gone, even when the call site still reads `quote.Net`. - A test that serializes the response and asserts on property names catches the defect before a client does; a test that only checks the C# values passes happily. The diagnosis takes one sentence once you know it: tuple names are compile-time decoration on declarations, and run-time machinery only ever meets `Item1` and `Item2` as fields.

  • Why does `dynamic d = quote; Console.WriteLine(d.Net);` throw in C#?
    The runtime binder resolves `Net` against the value's actual type, `ValueTuple<decimal, decimal>`, which has only the fields `Item1` and `Item2`. The names exist only in metadata on the declaring method, so the binder throws `RuntimeBinderException`. `d.Item1` works.
  • Would turning on JsonSerializerOptions.IncludeFields fix the empty JSON for a C# tuple?
    It stops the output being empty but writes `{"Item1":100,"Item2":20}`, because the serializer can only see the runtime field names. Clients still cannot find `Net` or `Tax`, and the wire contract now depends on tuple positions. A named type is the real fix.
  • When is returning a C# tuple from a method still the right call?
    When the caller is C# code that sees the declaration and uses the values at once: private and internal helpers, LINQ intermediates, `async` methods that need two results where `out` parameters are not allowed. Once the value is stored, serialized, logged or exposed publicly, give it a named type.

  • Tuple element names are stored in the value and visible to reflection on it.
  • System.Text.Json writes Net and Tax once IncludeFields is turned on.
  • The empty JSON means the tuple's values were lost before serialization.
  • Async methods can return several values through out parameters instead.
  • A C# 12 using alias for the tuple gives the JSON its property names.