Training - Beratung - Projektarbeiten

www.David-Tielke.de

Webcast C# 6.0 - Folge 4: Using Static

Die wohl merkwürdigste Erweiterung von C# 6.0 ist ohne Zweifel “Using Static”, also das direkte Einbinden von Membern eines statischen Typs in einen Namensraum. Dadurch entfällt der vermeidlich komplizierte Aufruf über den Klassennamen. Auch wenn ich ein großer Fan von C# 6.0 und dessen Erweiterungen bin, kann ich diesem Sprachfeature einfach nichts abgewinnen. Der Code dadurch mag kompakter werden, jedoch leidet die Lesbarkeit des Codes sehr stark und statische Member aus anderen Klassen sehen plötzlich so aus, wie Memberaufrufe auf dem aktuellen Typ – ein no-go!

Dazu aus der Project Roslyn Webseite

The feature allows all the accessible static members of a type to be imported, making them available without qualification in subsequent code:
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program
{
    static void Main()
    {
        WriteLine(Sqrt(3*3 + 4*4)); 
        WriteLine(Friday - Monday); 
    }
}
This is great for when you have a set of functions related to a certain domain that you use all the time. System.Math would be a common example of that. It also lets you directly specify the individual named values of an enum type, like the System.DayOfWeek members above. Extension methods Extension methods are static methods, but are intended to be used as instance methods. Instead of bringing extension methods into the global scope, the using static feature makes the extension methods of the type available as extension methods:
using static System.Linq.Enumerable; // The type, not the namespace
{
    static void Main()
    {
        var range = Range(5, 17);                // Ok: not extension
        var odd = Where(range, i => i % 2 == 1); // Error, not in scope
        var even = range.Where(i => i % 2 == 0); // Ok
    }
}
This does mean that it can now be a breaking change to turn an ordinary static method into an extension method, which was not the case before. But extension methods are generally only called as static methods in the rare cases where there is an ambiguity. In those cases, it seems right to require full qualification of the method anyway.
Links

Webcast C# 6.0 - Folge 3: Expression Bodied Function Member

Immer dann, wenn in C# eine Methode oder ein Computed-Property mit nur einem einzigen Statement geschrieben wird, erzeugt dies, bedingt durch den notwendigen Anweisungsblock nach Methoden oder Properties, unnötig viel Code. Ein ähnliches Problem existieren bei den in C# 2.0 eingeführten anonymen Funktionen. In C# 3.0 wurde deshalb mit den Lambdaausdrücken eine Kurzform hinzugefügt, bei der mit Hilfe eines Projektionsoperators, sehr kurze und knappe “Inlinemethoden” geschrieben werden können:

names.Where(n => n.Age >= 18);

Mit C# 6.0 und den “Expression Bodied Function Member”, existiert nun eine solche Variante auch für die direkte Deklarationen von Methoden und berechneten Eigenschaften.

Dazu aus der Projekt Roslyn Webseite:

Lambda expressions can be declared with an expression body as well as a conventional function body consisting of a block. This feature brings the same convenience to function members of types. Expression bodies on method-like members Methods as well as user-defined operators and conversions can be given an expression body by use of the “lambda arrow”:
public Point Move(int dx, int dy) => new Point(x + dx, y + dy); 
public static Complex operator +(Complex a, Complex b) => a.Add(b);
public static implicit operator string(Person p) => p.First + " " + p.Last;
The effect is exactly the same as if the methods had had a block body with a single return statement. For void-returning methods – and Task -returning async methods – the arrow syntax still applies, but the expression following the arrow must be a statement expression (just as is the rule for lambdas):
public void Print() => Console.WriteLine(First + " " + Last);
Expression bodies on property-like function members Properties and indexers can have getters and setters. Expression bodies can be used to write getter-only properties and indexers where the body of the getter is given by the expression body:
public string Name => First + " " + Last;
public Customer this[long id] => store.LookupCustomer(id); 
Note that there is no get keyword: It is implied by the use of the expression body syntax.
Links

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