loading experience

C#

C# 14: the field keyword in properties

Validate or transform a property value without declaring the private backing field by hand.

C# 14: the field keyword in properties

Auto-properties are handy until you need a little logic: at that point you had to declare a private field and write full get and set accessors. C# 14 introduces the field keyword, which represents the backing field generated by the compiler.

The field keyword removes the hand-written backing field.
The field keyword removes the hand-written backing field.

Before and after

// Before
private string _name = "";
public string Name
{
    get => _name;
    set => _name = value?.Trim() ?? "";
}

// With C# 14
public string Name
{
    get;
    set => field = value?.Trim() ?? "";
} = "";

Typical use cases

  • Normalisation: whitespace, casing, formats.
  • Validation: throw an exception if the value is not acceptable.
  • Change notification in MVVM apps.
public int Quantity
{
    get;
    set
    {
        ArgumentOutOfRangeException.ThrowIfNegative(value);
        field = value;
    }
}

Watch out for names

If a class already has a member called field, the keyword takes precedence inside accessors. In those cases you can use @field or this.field to refer to the existing member; the compiler reports ambiguities.

The result is shorter code, with the logic next to the property and no private fields scattered around the class.

Comments (0)

No comments yet.

Leave a comment