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@fieldto reference it andfieldfor the backing field - Works with both
getandset(orinit) accessors. You can usefieldin one and leave the other as auto-implemented