Movatterモバイル変換


[0]ホーム

URL:


Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Download Microsoft EdgeMore info about Internet Explorer and Microsoft Edge
Table of contentsExit focus mode

field - Field backed property declarations

  • 2024-11-14
Feedback

In this article

Important

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.

C# language specification

For more information, see theC# Language Specification. The language specification is the definitive source for C# syntax and usage.

Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, seeour contributor guide.

Feedback

Was this page helpful?

YesNo

In this article

Was this page helpful?

YesNo