Semi-Auto Property

Eintrag zuletzt aktualisiert am: 29.11.2024

Mit einem Semi-Auto Properties kann man Getter und/oder Setter implementieren ohne ein explizites Backing-Field zu müssen. Auf das vom Compiler automatisch erzeugte Backing Field nimmt man Bezug mit dem neuen Schlüsselwort field. Anstelle von set darf auch init verwendet werden. Man hat dann ein halbautomatisches Init Only Property. Ein halbautomatisches Property kann am Ende mit einem Wert initialisiert werden.

Hinweis

Diese neue Art von Property-Definitionen war schon für C# 11.0 (!) angekündigt. Jetzt in .NET 9.0 gibt es die dreizehnte Version des C#-Compilers, das Feature "Semi-Auto Properties" ist enthalten, hat aber den Status experimentell. Es ist daher nur verfügbar, wenn man in einer Projektdatei entweder <EnablePreviewFeatures>True</EnablePreviewFeatures> oder <LangVersion>preview</LangVersion> setzt.

Beispiel

class PersonWithID
{
/// <summary>
/// Auto Property
/// </summary>
public string Name { get; set; } = "unbekannt";

private string company = "Freelancer";
/// <summary>
/// Full Properties
/// </summary>
public string Company
{
get => company; set
{
if (value == null)
{
throw new ArgumentOutOfRangeException();
}
company = value;
}
}

/// <summary>
/// Semi-Auto Property
/// </summary>
public int ID
{
get;
set // init auch erlaubt!
{
if (value < 0) throw new ArgumentOutOfRangeException();
if (field > 0) throw new ApplicationException("ID schon gesetzt");
field = value;
}
} = -1;
}