New in .NET 10.0 [7]: Semi-Auto Properties in C# 14.0
The semi-auto properties, which were already experimental in C# 13.0, are a stable feature in C# 14.
(Image: Pincasso/Shutterstock)
- Dr. Holger Schwichtenberg
In the document “What’s new in C# 14,” Microsoft describes the keyword field, which can be used to create so-called semi-auto properties.
However, this language feature already exists in the stable version of .NET 9.0 – but in the “Preview” status. This means that you had to set <LangVersion>preview</LangVersion> for it. The mention in “What’s new in C# 14” suggests that the language feature will finally be considered stable in C# 14.0.
The following code shows a semi-auto property with the keyword field, which automatically creates a field for the property:
/// <summary>
/// Semi-Auto Property
/// </summary>
public int ID
{
get;
set // init wäre hier auch erlaubt!
{
if (value < 0) throw new ArgumentOutOfRangeException();
if (field > 0) throw new ApplicationException("ID schon gesetzt");
field = value;
}
} = -1;
Videos by heise
If there is already a data member named field in (older) program code, the compiler will warn that it is no longer being used. This may represent a breaking change, for example, if serialization exists for the data member field. However, developers can force the use of the old data member by writing @field or this.field in the program code.
(kbe)