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.

listen Print view
Roadmap with C#

(Image: Pincasso/Shutterstock)

1 min. read
By
  • 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.

The Dotnet Doctor – Holger Schwichtenberg
Der Dotnet-Doktor – Holger Schwichtenberg

Dr. Holger Schwichtenberg is the technical director of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with consulting and training services as well as software development, drawing on the expertise of 53 renowned experts. Thanks to his appearances at numerous national and international conferences, as well as more than 90 specialist books and over 1,500 specialist articles, Holger Schwichtenberg is one of the best-known experts for .NET and web technologies in Germany.

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.

In this code snippet, field is ambiguous.

(kbe)

Don't miss any news – follow us on Facebook, LinkedIn or Mastodon.

This article was originally published in German. It was translated with technical assistance and editorially reviewed before publication.