Training - Beratung - Projektarbeiten

www.David-Tielke.de

Webcast C# 6.0 – Folge 2: Read Only Auto Properties

Einer der Erweiterungen in C# 6.0, die sehr viel boilerplated Code vermeiden können, sind die Read Only Auto Properties.

Im zweiten Teil der Webcastreihe zu den Erweiterungen aus C# 6.0, widmen wir uns dieser genialien kleinen Erweiterung und zeigen wo sie eingesetzt werden sollte und wo nicht.

Dazu aus der Dokumentation des Roslyn-Projektes:

Auto-properties can now be declared without a setter.
public class Customer
{
    public string First { get; } = "Jane";
    public string Last { get; } = "Doe";
}
The backing field of a getter-only auto-property is implicitly declared as readonly (though this matters only for reflection purposes). It can be initialized through an initializer on the property as in the example above. Also, a getter-only property can be assigned to in the declaring type’s constructor body, which causes the value to be assigned directly to the underlying field:
public class Customer
{
    public string Name { get; }
    public Customer(string first, string last)
    {
        Name = first + " " + last;
    }
}
This is about expressing types more concisely, but note that it also removes an important difference in the language between mutable and immutable types: auto-properties were a shorthand available only if you were willing to make your class mutable, and so the temptation to default to that was great. Now, with getter-only auto-properties, the playing field has been leveled between mutable and immutable.

 

Links

Kommentar schreiben

Loading