This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
field
- Field backed property declarationsImportant
Thefield
keyword is a preview feature in C# 13. You must be using .NET 9 and set your<LangVersion>
element topreview
in your project file in order to use thefield
contextual keyword.
You should be careful using thefield
keyword feature in a class that has a field namedfield
. The newfield
keyword shadows a field namedfield
in the scope of a property accessor. You can either change the name of thefield
variable, or use the@
token to reference thefield
identifier as@field
. You can learn more by reading the feature specification forthefield
keyword.
The contextual keywordfield
, 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 aget
orset
accessor and let the compiler generate the other accessor as it would in an automatically implemented property.
The addition of thefield
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 theHours
property as an automatically implemented property. Then, you discover that you want to protect against a negative value. You usefield
and provide range checking in theset
accessor. You don't need to declare the backing field by hand and provide a body for theget
accessor.
For more information, see theProperties andIndexers articles.
For more information, see theC# Language Specification. The language specification is the definitive source for C# syntax and usage.
Was this page helpful?
Was this page helpful?