C Sharp 6 features (Tech Ed New Zealand 2014)

C# 6 at Tech Ed

Perhaps, one of the most interesting presentations at this year's Tech Ed (2014) was the one on the expected features in C# 6.0. Lucky enough to have been there, courtesy of my employer, Zeacom, I took the liberty to document everything that was learned, although please bear in mind that a lot of it is subject to change and may not even make it in the release version. And so, without further ado...

Automatic property initializers

In C# 6, we'll be able to initialize automatic properties (even those without a setter) much like we do with fields in previous versions. This makes a lot of sense. Rather than doing it in the constructor, or explicitly declaring a backing field and giving it a default value, specifying the value right after the property declaration seems to be rather convenient. See example below.

public class DummyClass
{
    public int DummyProp { get; } = 3;
}

 

Lambda members

Perhaps inspired by the commonplace affection towards the lambda methods, we're being granted the option to declare the body of a member as a lambda expression. This means that the IDE will happily accept definitions of methods and properties in the following form:

public class Dummy
{
    public long ToLong(int value) => (long)value;
    public string Foo => "bar";
}

 

Constructor following type name

Some more syntactic sugar thrown into the mix. Instead of declaring constructor the usual way, C# 6 promises making it valid to specify the signature right after a class or a struct name.

public class Dummy(string foo, int bar)
{
    public string Foo { get; } = foo;
    public int Bar { get; set; } = bar;
}

 You can see that it can be combined with automatic property initializers.

Consequently, passing parameters to a base class is as simple as:

public class Foo : Bar(123, "meh")
{

}

 It's expected that you should be able to do something like this with multiple constructors:

public class Foo (string mmmk)
{
    public string UsefulProp { get; } = mmmk;

    public Foo(string whatevs, float away)
        : this(whatevs)
    {
    }
}

 

 Inline variable declaration for out parameters

Many times we wished that we could do this (even if subconsciously), because it would save us a whole one line of code, but also there is little reason why it shouldn't be possible if the variable is used only after the method returns:

if(int.TryParse("googolplex", out var result))
    return result;

 

 

Null propagation operator

I've personally heard other, admittedly smart, developers expressing their desire for such a feature before, and it may finally be making its way into C# 6. Instead of checking a reference for null before accessing its members, there's a new syntactic sugar way of doing it:

return (Customer?.Name?.First) ?? "random joe";

 

What's interesting (and logical) about this is that the return type of such an expression will always be Nullable<> for structs. Consider this:

int? someRandomValue = customer?.Name?.First?.Length;

 Since any one of the operands in the chain can be null, a value is not guaranteed, thus forcing the type of the target variable to be nullable.

Similarly, the null propagation operator is not constricted to assignment operations. Methods can also be called in a similar fashion:

public static void RunUselessMethod(DumbClass junk)
{
    junk?.ProduceMore();
}

  

Digit separators

Haven't you wanted to be able to define numeric literals with digit separators in them? No? Well, C# 6 may allow for that, just in case you ever need it.

public static class UsefulStuff
{
    public const int LotsaNulls = 1_000_000_000;
}

 

 Binary literals

Binary literalals might be making their way into C# 6 and are a convenient way of defining a number using binary form:

public static class UsefulStuff
{
    public const int SomeMask = 0110_1001;
}

 

 

Indexer-style initialization syntax

For those that are tired of old ways of initializing collections, there may be a new way in C# 6 (indexer-style):

return new Dictionary<int, double>
{
    [0] = 0,
    [30] = 0.5,
    [45] = Math.Sqrt(2) / 2,
    [60] = Math.Sqrt(3) / 2,
    [90] = 1
};

 

Params IEnumerable<>

It may be possible to declare the params argument as IEnumarable rather than T[], which would then allow to pass an IEnumerable into such a function. Can be especially useful with LINQ.

public static void PrintStrings(params IEnumerable<string> strings)
{
    foreach(var str in strings)
        Console.Writeline(str);
}

//Should be usable in the following forms
PrintStrings("foo", "bar", "baz");
PrintStrings(customers.Select(item => item.Name));

 

 

Semicolon operator in inline lambda methods

C# 6 may finally support a way of defining multiple statements in an inline lambda expression separated by a semicolon. Note, that the result of the last statement is probably the return value.

public static IEnumerable LogAndReturn(IEnumerable strings)
{
    return strings.Select(s => Console.WriteLine(s); "Hello " + s));
}

 

 

Possible shorthand syntax for String.Format

There's a possible addition of new syntax for formatting a particular string with values in C# 6. E.g.

public string FormatMe(int foo, long bar)
{
    //Instead of doing:
    return string.Format("{0} {1}", foo, bar);
    //This could be the shorthand way of doing it
    return string.Format($"{foo} {bar}");
}

 

 

Operator "nameof()"

One particularly useful great new operator making its way into C# 6 is the nameof operator. How many times have we wished we could specify the name of a particular member, parameter or variable by referencing it in the code, taking advantage of compile time checking. In C#6 there's a new operator exactly for this purpose: nameof(). There are multiple scenarios, where this can be useful, such as with INotifyPropertyChanged, ArgumentNullException and reflection. E.g.

public void DoSomething(Foo value)
{
    if(value == null)
        throw new ArgumentNullException(nameof(value));
}

 

 

Collection initialization via extension methods

There are cases where custom collections are difficult to initialize because they don't implement standard interfaces and methods. So what if there was a collection named BadlyDesignedCollection with just a method, let's call it "append". In C#6 to initialize such a collection, in theory, we could write an extension method named "Add" and it would allow us to initialize it as usual. See example below.

public class BadlyDesignedCollection
{
    private List<object> m_list = new List<object>();

    public void Append(object value)
    {
        m_list.Add(value);
    }
}

public static class Extensions
{
    public void Add(this BadlyDesignedCollection collection, object value)
    {
        collection.Append(value);
    }
}

public class Example
{
    public BadlyDesignedCollection CreateCollection()
    {
        return new BadlyDesignedCollection()
        {
            "Total",
            "Foo",
            "Bar"
        };
    }
}

 

 

Exception handling filters

Ever desired to only catch an exception if it met a certain condition besides its type? Well, C# 6 proposes a way of doing that in the form similar to:

public static void ReadFile()
{
    try
    {
        File.ReadAllText("meh.txt");
        File.ReadAllText("err.txt");
    }
    catch (FileNotFoundException ex) if (ex.FileName.EndsWith("zomg"))
    {
        System.Console.WriteLine("lawl");
    }
}

 

Constructor type inference

This one sounded particularly useful to me, as I can actually recall situations where I needed it. C# 6 is expected to support generic type inference in constructors. The example below is self-explanatory.

public static void TupleMe()
{
    // Before
    var tuple = new Tuple<string, int>("bob", 123);

    // Workaround
    tuple = Tuple.Create("bob", 123);

    // In C# 6
    tuple = new Tuple("bob", 123);
}

  

Switch statements on types

This can be quite useful where type resolution is necessary, typically in special cases, such as reflection and dynamic compilation using expressions. I wouldn't imagine this to be required for business logic, as that's what polymorphism (virtual methods) is for. I have seen some developers write a series of if statements for branching business logic based on the specialized sub-type of objects sharing the same base interface and class. And that's, in my view, nothing but misunderstanding of OO principles. .NET framework already handles type resolution for us, let it do its job. Have type-specific logic in a specialized class. 

The switch statements on types are expected to look like this (also the implementation details are a bit murky at this point):

public string ResolveType(object o)
{
    switch(o)
    {
        case o as string:
            return "I'm a string.";
        case o as int:
            return "I'm an int.";
        case o as UselessType:
            return "I'm a UselessType.";
    }
}

  

 

Branching on object type

Branching on the type of objects using if statements appears to have also been simplified in C# 6. See below:

public static void BranchOnType(object o)
{
    if(o is int i)
    {
        Console.Writeline("integer " + i);
    }
    else if(o is string s)
    {
        Console.Writeline("string " + s);
    }
}

  

 

Implementing custom syntax analyzer

Surely, every one of us has wished to define our own syntax rules for the compiler to follow! No? Well, there could be a way in C# 6 - just think of the possibilities! I couldn't tell you more about this feature at this stage, as it wasn't extensively covered, but, in theory, a starting point would be to declare a class similar to the following:

[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer(LanguageNames.CSharp)]
internal class DiagnosticAnalyzer : ISyntaxNodeAnalyzer
{
    //...
}

  

The future of C#

It's obvious that the language is being actively supported and improved with every iteration. Whether all of these additions are beneficial, I'll leave to you to judge. I can certainly see myself taking advantage of most of the new features without a doubt, as I frequently found them lacking before. The obvious ones are: constructor type inference, inline out variable declaration, semicolon in lambdas, lambda-style member bodies, automatic property initialization, null propagation operator, switch statement on types and nameof operator. So that's most of them. I'll certainly find the use for the rest at some point. C# is by far my favourite language (the syntax highlighter used in this article was written by me specifically for it), therefore it's highly reassuring and encouraging that the Microsoft development team behind it has such a nurturing attitude towards it, being open to and considerate of the community feedback. With the number of C# questions and answers continually increasing on sites like Stack Overflow, the ever growing developer base, and largely thanks to the sheer elegance, refinement, stability and power of the language, the only logical conclusion that can be made is - the future of C# looks intensely bright!!






Information Error Confirmation required