skip to content

In C# 14, how does the field keyword let a Nights property validate its setter without a declared backing field, and what skips that validation?

level: middleimportance: should knowfreq 25%

answer

  1. compiler-made storage, now nameable
  2. automatic get, hand-written set
  3. initializers write storage directly
  4. constructor assignments call set
  5. properties only, not indexers

basics

~20 s

In C# 14, field names the compiler-synthesized backing field inside a property accessor, so get; stays automatic while set validates and assigns field. A property initializer skips the setter and writes the backing field directly.

solid answer

~40 s

C# 14's contextual keyword `field` refers to the hidden backing field from inside a property's accessors, so `public int Nights { get; set { ArgumentOutOfRangeException.ThrowIfLessThan(value, 1); field = value; } }` validates every assignment without declaring `_nights`. Because only the accessors can name that field, other members of the class cannot bypass the check by writing it directly. What skips the check is a property initializer: `= 0` after the closing brace stores straight into the backing field, while an assignment in a constructor body or an object initializer does call the setter. The keyword works in `get`, `set` and `init` accessors of properties, not of indexers, and an existing member named `field` now needs `this.field` or `@field` inside accessors (warning CS9258).

code

csharp · 21 lines
csharp
var booking = new HotelBooking();
Console.WriteLine($"after the initializer: {booking.Nights}");   // 0 got in unchecked

try { booking.Nights = 0; }
catch (ArgumentOutOfRangeException ex) { Console.WriteLine($"setter rejected {ex.ParamName}"); }

booking.Nights = 4;
Console.WriteLine($"after a valid set: {booking.Nights}");

public class HotelBooking
{
    public int Nights
    {
        get;
        set
        {
            ArgumentOutOfRangeException.ThrowIfLessThan(value, 1);
            field = value;
        }
    } = 0;   // a property initializer writes the backing field and skips set
}

go deeper

for a junior

Recall that in C# 14 field inside a property accessor means the compiler's hidden backing field, so you can add a check to a setter without declaring a field.

for a middle

Explain how auto and full accessors mix, why a property initializer bypasses the setter, and that constructor and object-initializer assignments do run it.

for a senior

Review field-backed properties for initializers that skip validation and for an existing member named field that changes binding under C# 14 with warning CS9258.

for a principal

Decide when a team adopts field: it removes boilerplate once every project compiles with C# 14, while shared storage, ref access and older language versions still call for named fields.

## The problem `field` solves Before C# 14 a property had two shapes. An **auto-property**, `public int Nights { get; set; }`, got compiler-generated storage but no room for logic. As soon as the setter needed a check, you rewrote it as a **full property** with an explicit field: ```csharp private int _nights; public int Nights { get => _nights; set { ArgumentOutOfRangeException.ThrowIfLessThan(value, 1); _nights = value; } } ``` That costs a declaration, keeps the field name in sync by hand, and leaves `_nights` visible to every method in the class, any of which can write `_nights = 0` and bypass the check. ## What `field` refers to In C# 14, `field` is a **contextual keyword** that, inside a property accessor, denotes the **compiler-synthesized backing field** of that property: - an accessor may use `field` in a full body while the other accessor stays automatic, as in `{ get; set { ...; field = value; } }`; - it works in `get`, `set` and `init` accessors and in expression-bodied properties, for example a lazy `public string Summary => field ??= BuildSummary();`; - the backing field has the property's type and is reachable only from that property's accessors, so the rest of the class cannot write it by accident; - `[field: SomeAttribute]` on the property targets that backing field, as it already did for auto-properties; - an overriding property that uses `field` gets its own backing field, separate from the base property's. ## Where the validation runs, and where it does not | Assignment | Goes through `set`? | |---|---| | Property initializer `{ ... } = 0;` | **no**: writes the backing field directly | | `Nights = 0;` in a constructor body | yes | | `new HotelBooking { Nights = 0 }` | yes | | `booking.Nights = 0;` from any method | yes | The initializer rule is deliberate. Initializers run before the base constructor, when calling an instance method such as a setter is not allowed, so the compiler stores the value straight into the backing field. The consequence is easy to miss in review: the validated property in the example below starts life at `0`, a value its own setter would reject. If the starting value must be validated, assign it in a constructor instead. ## Rules and limits - **Properties only.** Indexers have no synthesized backing field; inside an indexer accessor `field` is an ordinary name, so it fails with CS0103 when nothing declares it. - **It is a keyword in accessors.** Declaring a local named `field` there is error CS9273; `nameof(field)` does not compile (CS8081). - **Existing members named `field`.** In C# 14 `field` inside an accessor binds to the backing field, so a class that already had a member called `field` changes meaning and the compiler warns with CS9258; write `this.field` or `@field` to keep the old binding. Keywords added in recent releases are covered with the C# 12–14 additions. - **Language version.** With `LangVersion` 13 the same code fails with CS9260, "Feature 'field keyword' is not available in C# 13.0". - **Nullable analysis** checks the setter like a small constructor for the backing field, and a getter such as `field ??= ...` that never returns null does not trigger CS8618 in the class's constructors. ## When to keep an explicit field `field` covers the common case of one property owning one piece of state. Keep a named private field when: 1. several members read or write the same storage, as a cache invalidated from two setters does; 2. a method needs the field as a `ref` argument, for example `Interlocked.Exchange(ref _nights, value)`; 3. the code must still compile with C# 13 or earlier. ## Reading the example The snippet below is the hotel booking's `Nights` property after a reviewer asked for "at least one night" to be enforced: - `get;` stays automatic and returns the synthesized backing field; - `set` calls `ArgumentOutOfRangeException.ThrowIfLessThan(value, 1)` (.NET 8) and only then assigns `field`; - the trailing `= 0` is a property initializer, so a fresh booking reports `0` nights without the setter ever running; - `booking.Nights = 0` afterwards does run the setter and throws, with `ParamName` equal to `"value"` because the guard captures the argument expression. The fix the review should ask for is either to drop the initializer, leaving the default to be replaced through the setter, or to start at a valid value such as `= 1`, so that every value the property can hold passes its own rule.

  • Can field implement a lazily computed read-only property?
    Yes: `public string Summary => field ??= BuildSummary();` stores the result in the synthesized field on the first read and returns it afterwards. Because the getter never returns null, nullable analysis treats the property as null-resilient and does not report CS8618 in the class's constructors, even though nothing assigns `Summary` there.
  • What happens to a class that already has a member named field when it moves to C# 14?
    Inside property accessors, `field` now means the synthesized backing field, so `get => field;` silently stops reading the old member and reads new, empty storage. The compiler reports warning CS9258 at each such use; writing `this.field` or `@field` restores the old binding.

  • The field keyword can be used in any method of the class, not only in property accessors.
  • A property initializer such as = 0 runs the custom setter, so the value is validated.
  • Using field means writing bodies for both the get and the set accessor.
  • field works inside an indexer's accessors to reach the indexer's storage.
  • The field keyword shipped in C# 13 together with partial properties.

Assumes C# 14 (.NET 10); the field keyword is new in C# 14, and LangVersion 13 rejects it with CS9260.