Looking at the new features in C# 6.0

Update: There were some changes to the language feature set that removed the features Primary Constructors and Declaration expressions. I removed them from this blog post as well to avoid confusion.

Because Sundays are boring I thought I'd spend the evening testing the new language features brought into C# with C# 6.0.

You can see a full list of new features implemented in C# 6.0 so far over at roslyns site at codeplex. You can find discussions on future features that are under consideration over there as well.

The examples below and in my C# 6.0 playground repo only work in Visual Studio 2015 Preview. You can download Visual Studio 2015 Preview here. Alternatively you can use your favorite text editor, combined with the new vNext commands k and kpm to run and build it.

Auto-property initializers and Getter-only auto-properties

These two features is pretty simple, but can save a lot of code lines! Use it with primary constructors to produce consise beatiful code like this:

public class User(string name, string email)
{
      public string Name { get; } = "anders";
      public string Email { get; } = "anders.slinde@domain.com";
}

Using static members

To further reduce the verbosity of C# programs you can now use static members of classes you reference without putting the class name in front of your member-call.

using System.Console;

public class UsingConsole
{
    public static void WriteStuff()
    {
        WriteLine("Stuff is written to the console");
    }
}

In this example the WriteLine method calls the Console.WriteLine method and writes the text to the console.

If you change the using statement to

using System.Diagnostics.Debug;

which also has a WriteLine method, it will write the text to the debug window.

If you want to use both Console and Debug in a class you need to specify which static member your code is referring to.

Exception filters

F# and VB has this feature already. It allows you to add an if-block to your catch statements. This means you can add additional logic that determines if you catch the exception or not. It will also allow you to do side-effects like logging.

private void ThisJustThrows() { throw new ArgumentException("oh noes"); }
    
public string DoSomething() 
{
    try { ThisJustThrows(); }
    catch (Exception e) if (e.Message == "oh noes" || Log(e))
    { 
        return "oh noes";
    }
    return "all is fine I guess";
}

private bool Log(Exception e) { /** call your logger **/ return false; }

Null propagation

One of the most popular and, in my opinion, exciting new features. This allows you to add a ? after accessing a variable or property to perform a null-check that propagates forward.

public class User(string name, string email)
{
    public string Name { get; } = name;
    public string Email { get; } = email;

    public List<Post> Posts { get; set; }

    public int? GetComments(int postId)
    {
        return Posts?.FirstOrDefault(x => x.Id == postId)?.Comments?.Count();
    }
}

public class Post
{
    public List<Comment> Comments { get; set; }
    public int Id { get; set; }
}

public class Comment
{
    public string Text { get; set; }
}

In the method GetComments the return statement propagates the null forward. If any of the nested data structures are null the return statement will return null, instead of throwing a null pointer exception.

Await in catch/finally

Pretty straight forward. This is probably one of those features that were difficult to implemenet before the compilre rewrite done in the new Roslyn compiler. Now we have it.

public async Task TryAServiceCall()
{
    try { await PerformServiceCall(); }
    catch { await AsyncLogging(); }
    finally { await CleanUp(); }
}

Expression-bodied members

This feature adds shorthand for computing values of your properties in the get statement:

public int Size => _x * _y;