Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The contextual keyword field, added in C# 14, 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.