Skip to content

Field keyword C# 14.0code reductioncorrectness

Reference the synthesized backing field of an auto property using the field keyword.

The field keyword, previewed in C# 13.0, is now generally available. It references the compiler-synthesized backing field of an auto property, letting you add custom logic to a getter or setter without declaring a separate backing field.

Code

C#
class Post
{
    public string Title
    {
        get;
        set => field = !String.IsNullOrEmpty(value)
                            ? value
                            : throw new ArgumentException("Must not be empty.", nameof(value));
    }

    public int ViewCount
    {
        get => field;
        set => field = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
    }
}
C#
class Post
{
    private string title;
    public string Title
    {
        get => title;
        set => title = !String.IsNullOrEmpty(value)
                            ? value
                            : throw new ArgumentException("Must not be empty.", nameof(value));
    }

    private int viewCount;
    public int ViewCount
    {
        get => viewCount;
        set => viewCount = value >= 0 ? value : throw new ArgumentOutOfRangeException(nameof(value));
    }
}

Notes

  • Eliminates the need for a manually declared backing field when only simple validation or transformation is needed
  • If you have an existing member named field, use @field to reference it and field for the backing field
  • Works with both get and set (or init) accessors. You can use field in one and leave the other as auto-implemented

More information