Semi-Auto Property
Fachbücher zum Thema Semi-Auto PropertyHinweisDiese 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.
Beispielclass 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;
}
{
/// <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;
}
Aktualisiert: 29.11.2024