skip to content

In C#, what does a record's synthesized ToString print, and how do you mask a PaymentCard record's card number in it?

level: middleimportance: should knowfreq 45%

answer

  1. type name, then braces
  2. public fields and readable properties
  3. each value's own ToString
  4. PrintMembers builds the inside

basics

~20 s

It prints the type name and each public instance field and readable property as Name = value inside braces, formatting values with their own ToString. To mask a member, declare PrintMembers(StringBuilder) yourself, or override ToString.

solid answer

~40 s

The synthesized `ToString` creates a `StringBuilder`, appends the record's name and ` { `, calls `PrintMembers(builder)` and closes with `}`. `PrintMembers` appends `Name = value` for every public non-static field and readable property, positional or declared in the body, separated by `, `; a nested record prints its own braces, and a `List<T>` or array prints only its type name. A card number would therefore reach every log line that formats the record. Declare `protected virtual bool PrintMembers(StringBuilder builder)` (private in a sealed record, `protected override` in a derived one) and append a masked value; the generated `ToString` and any derived record's `PrintMembers` use it. Overriding `ToString` instead replaces the whole format, and since C# 10 that override may be `sealed`, which stops derived records from generating their own.

code

csharp · 20 lines
csharp
using System.Text;

var line = new OrderLine(new Money(3m, "EUR"), 2, ["gift"]);
Console.WriteLine(line);
// OrderLine { Price = Money { Amount = 3, Currency = EUR }, Quantity = 2, Tags = System.String[] }

Console.WriteLine(new PaymentCard("4111111111111111", "Ana"));
// PaymentCard { Number = ****1111, Holder = Ana }

public record Money(decimal Amount, string Currency);
public record OrderLine(Money Price, int Quantity, string[] Tags);

public record PaymentCard(string Number, string Holder)
{
    protected virtual bool PrintMembers(StringBuilder builder)
    {
        builder.Append($"Number = ****{Number[^4..]}, Holder = {Holder}");
        return true;
    }
}

go deeper

for a junior

Know the shape TypeName { Prop = value, ... }, that it lists public members, and that a record may override ToString.

for a middle

Explain the split between ToString and PrintMembers, which members print, and the PrintMembers signature for sealed, non-sealed and derived records.

for a senior

Treat generated ToString as a data-leak path in logs, mask sensitive members in PrintMembers, and use sealed ToString when a hierarchy needs one format.

for a principal

Decide whether records carrying personal or payment data may rely on the generated ToString at all, and make that check part of code review.

## What the generated ToString does Every record class gets an override of `object.ToString()` and a helper, `PrintMembers(StringBuilder builder)`. The split matters, because the helper is the part you usually replace. The generated `ToString`: 1. creates a `StringBuilder`; 2. appends the record type's name followed by ` { `; 3. calls `PrintMembers(builder)` and appends a space if it returned `true`; 4. appends `}` and returns the string. `PrintMembers` writes the inside. For each **printable member**, meaning a public non-static field or a public readable property, it appends the member name, ` = ` and the value, separated by `, `. Value-type members are converted with their own `ToString()`; reference-type members are appended through their `ToString()` too, with `null` printing as nothing. The result looks like `Money { Amount = 12.50, Currency = EUR }`. ## What ends up in the output | Member | Printed? | |---|---| | positional property | yes | | public property declared in the body | yes | | public instance field | yes | | `internal`, `protected` or `private` member | no | | `static` member | no | | property whose type is another record | yes, through that record's own `ToString`, braces and all | | `List<T>` or array property | yes, but only as its type name, such as `System.String[]` | Two consequences come up in code review: - **Formatting follows the current culture.** A `decimal` prints through `decimal.ToString()`, so `12.50m` reads `12.50` under the invariant culture and `12,50` under a culture with a comma separator. Record `ToString` is diagnostic text, not a format to parse or persist. - **Everything public is printed.** A log call or an interpolated string that formats a record writes every public member, including a card number, an email address or an access token. ## Changing the output with PrintMembers Declaring `PrintMembers` keeps the `TypeName { ... }` frame and changes only the inside. The signature depends on where the record sits: - a record that is **not sealed** and derives from `object`: `protected virtual bool PrintMembers(StringBuilder builder)`; - a **sealed** record that derives from `object`: `private bool PrintMembers(StringBuilder builder)`; - a record that derives from another record: `protected override bool PrintMembers(StringBuilder builder)`. Any other accessibility is rejected: a `private` one in a non-sealed record fails with CS8872 and CS8875, and a `public` one with CS8875 (`Record member ... must be protected`). Return `true` when you appended something, so the generated `ToString` adds the closing space. For an order-history `PaymentCard(string Number, string Holder)`, the replacement appends `Number = ****1111, Holder = Ana` and nothing else. Because derived records call the base `PrintMembers` first, the masking also holds for any record that later derives from `PaymentCard`. ## Overriding ToString, and sealing it You may override `ToString()` itself when you want a different frame altogether, for example `PremiumCustomer #7`. In a hierarchy there is a catch: every derived record normally synthesizes its own `ToString`, which would discard the base's format. Since **C# 10**, the base may declare `public sealed override string ToString()`. Then: - derived records get no synthesized `ToString`, and the base's runs for every instance; - a derived record that tries to override it fails with **CS0239** (`cannot override inherited member ... because it is sealed`); - derived records still get a synthesized `PrintMembers` for their own members, so a base `ToString` that calls `PrintMembers` keeps printing them. Under `LangVersion` 9, the `sealed` modifier on a record's `ToString` is rejected with CS8773 (`Feature 'sealed ToString in record' is not available in C# 9.0`). ## Inheritance order A derived record's synthesized `PrintMembers` calls `base.PrintMembers(builder)` first, appends `, ` when the base printed something, then its own members. The type name is the run-time type's: a `PremiumCustomer` held in a `Customer` variable prints `PremiumCustomer { Id = 7, Name = Ana, DiscountPercent = 10 }`, with base members before derived ones. ## What to say in an interview Describe the frame and the helper, list which members print, mention that collections print as type names and values follow the current culture, and give `PrintMembers` with the right signature as the way to hide a sensitive member. Mention `sealed ToString` (C# 10) for hierarchies that need one format.

  • In C#, what changes in a derived record's ToString output?
    The derived record's synthesized `PrintMembers` calls the base `PrintMembers` first and then appends its own members, so `PremiumCustomer { Id = 7, Name = Ana, DiscountPercent = 10 }` lists base members first under the run-time type's name. If the base declared `sealed override ToString()` (C# 10 and later), the derived record gets no `ToString` of its own and overriding it is error CS0239.
  • Why can a C# record with a decimal Amount print differently on two machines?
    The synthesized `PrintMembers` formats value-type members with their own `ToString()`, which uses the current culture. `12.50m` prints as `12.50` under the invariant culture and `12,50` under a culture with a comma decimal separator. Treat record `ToString` as diagnostic output, and use a serializer or an explicit format with a fixed culture for anything stored or compared.

  • A record's ToString prints only its positional parameters.
  • Private fields appear in a record's generated ToString output.
  • A record's ToString lists the elements of a List property.
  • Declaring PrintMembers also requires overriding ToString.
  • Record ToString output is stable enough to parse or store.