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

Kommentar schreiben

Loading