field
- Field backed property declarations
Important
The field
keyword is a preview feature in C# 13. You must be using .NET 9 and set your <LangVersion>
element to preview
in your project file in order to use the field
contextual keyword.
You should be careful using the field
keyword feature in a class that has a field named field
. The new field
keyword shadows a field named field
in the scope of a property accessor. You can either change the name of the field
variable, or use the @
token to reference the field
identifier as @field
. You can learn more by reading the feature specification for the field
keyword.
The contextual keyword field
, added as a preview feature in C# 13, can be used in a property accessor to access the compiler synthesized backing field of a property. This syntax enables you to define the body of a get
or set
accessor and let the compiler generate the other accessor as it would in an automatically implemented property.
The addition of the field
contextual keywords provides a smooth path to add benefits such as range checking to an automatically implemented property. This practice is shown in the following example:
class TimePeriod4
{
public double Hours {
get;
set => field = (value >= 0)
? value
: throw new ArgumentOutOfRangeException(nameof(value), "The value must not be negative");
}
}
You might implement the Hours
property as an automatically implemented property. Then, you discover that you want to protect against a negative value. You use field
and provide range checking in the set
accessor. You don't need to declare the backing field by hand and provide a body for the get
accessor.
For more information, see the Properties and Indexers articles.
C# language specification
For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.