The field keyword 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.
It is generally available in C# 14.0.
Code
csharp
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));
}
}csharp
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