.NET Infoday: What's New in C# 6?

Thursday, December 4, 2014 by Rainer Stropek

At IT-Visions' .NET InfoDay 2015 in Graz, my friend Roman Schacherl and I will do a session about new features in C# 6. In this blog article I summarize the content of the talk and make the sample available for download.

Introduction

The upcoming version of C# will bring some convenient features for every-day coding. You should not expect such ground-breaking changes* like async/await. However, your C# code will be easier to write and easier to read if you make use of the new features.

In our session we cover the following new C# topics:

  • Null-conditional Operator
  • nameof Operator
  • Dictionary Initializers
  • Auto-Property initializers
  • Expression Bodied Functions and Properties
  • Static Using Statements - not covered here as we are no big fans of this feature ;-)
  • Exception-Handling (async, exception filters)
  • String Interpolation

*) In fact, you can. With Visual Studio 2015, Microsoft puts Roslyn, their brand new compiler platform for C# and Visual Basic, into production. This new platform is a real game-changer for language- and programming-tools around C# and VB. Our talk and therefore this article do not cover Roslyn.

Sample

Roman prepared a sample for our talk based on which we show all the new features of C# 6 mentioned above. I added this sample to my GitHub Samples repository. You can download it from there.

Null-conditional Operator

Basic Usage

Imagine the following code sample (Program.cs):

public class Program
{
    private static IList<Theme> themes;

    static void Main(string[] args)
    {
        InitializeThemes();
        DoSomethingWithCSharp6();
    }

    private static void DoSomethingWithCSharp6()
    {
        // Read theme from application settings and look it up in theme directory
        var themeConfig = ConfigurationManager.AppSettings["Theme"].ToLower();
        var theme = themes.FirstOrDefault(p => p.Name == themeConfig);

        Console.ForegroundColor = theme.ForegroundColor;
        Console.BackgroundColor = theme.BackgroundColor;
    }

    private static void InitializeThemes()
    {
        themes = new List<Theme>()
        {
            new Theme("dark", ConsoleColor.Black, ConsoleColor.White),
            new Theme("light", ConsoleColor.White, ConsoleColor.Black),
            new Theme("winter", ConsoleColor.Gray, ConsoleColor.Gray) // everything's gray in Austrian winter.
        };
    }
}

Note line 23. If the app.config file does not contain the Theme setting, we will get a null reference exception.

The reason is obious. AppSettings["Theme"] returns null and therefore the call to ToLower is invalid. In old versions of C# you would have to add an if statement. With C# 6, you can just add a "?", the null-conditional operator: var themeConfig = ConfigurationManager.AppSettings["Theme"]?.ToLower();

This change will solve the null referencing problem. However, the result stored in themeConfig will be null. Even with the "?", you will still have to write code to handle this null value. One option is the good old null coalesce operator. The following code snippet would fall back to the "light" theme if not app settings are present.

Multiple Null Conditional Operators in a Single Expression

You can also combine multiple null conditional operators in a single expression.

However, you have to note that whenever you use the new operator, the return type will be nullable (in this case Nullable<ConsoleColor> instead of ConsoleColor).

The new null conditional operator is also handy with arrays as shown in the following code snippet (for test purposes I added a null pointer to the themes array to generate the following screenshot):

Null Conditional Operator Behind the Scenes

So what happens behind the scene? Let's look at the generated IL code (see following screenshot). Note the brtrue.s statments that are added to handle null values (see details about IL statements in Wikipedia). This IL operation goes to the specified target if the value is true (i.e. not null).

Null Conditional Operator and Delegates

The null conditional operator is also usable with delegates. The typical example is an implementation of INotifyPropertyChanged as shown in the following code snippet:

public string Name
{
    get { return NameValue; }
    set
    {
        if (NameValue != value)
        {
            NameValue = value;

            // Instead of:
            // if (PropertyChanged != null)
            // {
            //     PropertyChanged(this, new PropertyChangedEventArgs("Name"));
            // }
            // you can now write:
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Name"));
        }
    }
}

Nameof Operator

Speaking of INotifyPropertyChanged: CallerMemberName has been a usefull addition in this context in the past. However, there are many situations where it is not sufficient. Enter nameof, a new C# operator:

Note that the compiler simply replaces nameof(Name) with the string "Name" during compile time.

Dictionary Initializers

Our Theme class can be used to demo the next C# 6 feature: You can now initialize dictionaries like you are used to initialize lists:

Auto-Properties Initializers

In a world that depends more and more on parallel and asnyc programming, immutable objects have become more and more important. Before C# 6, you had to add a private setter to initialize auto properties. In C# this is no longer necessary. Let's apply this to our Theme class. Note that the color-related property is set in the constructor although they do not have setters.

Expression Bodied Functions and Properties, String Interpolation

We can further enhance our Theme class. First, we can use a new feature called expression bodied properties to shorten the code necessary for our FullName property. In analogy you can also define methods like this. Additionally we can greatly enhance the string building code. Instead of string.Format we use the new string interpolation feature which makes our code much easier to read and maintain.

Exception Handling

Last but not least Microsoft has enhanced C#'s exception handling code. Firstly, C# 6 enables you to use async methods with await inside of a catch block. Think of an async logging API you would like to use. C# makes consuing it very easy. Additionally, C# 6 allows us to filter the exceptions that should be caught not only based on the exception's type.

Start Evaluating C# 6 and VS2015

Interested? You can easily try Visual Studio 2015 Preview in Microsoft Azure. Microsoft provides a ready-made VM image that is ready for your experiments within a few minutes:


comments powered by Disqus

Rainer Stropek

Rainer Stropek

Co-founder, architect, developer

Bio

I am co-founder and CEO of the company software architects and have been serving this role since 2008. At software architects my team and I are developing the award-winning SaaS solution time cockpit. Previously, I founded and led IT consulting firms that worked in the area of developing software solutions based on the Microsoft technology stack.

In my work I focus on .NET development and software architecture. I have written some books and articles on C#, database development, Windows Azure, Windows 8 development, WPF, and Silverlight. Regularly I speak at conferences, do workshops and conduct trainings in Europe and the US. Since 2010 I have been MVP for Windows Azure.

I graduated the Higher Technical School Leonding (AT) for MIS with honors and hold a BSc (Hons) Computer Studies of the University of Derby (UK).

Contact

Twitter: @rstropek
Facebook
Google+
Xing
LinkedIn

Authors