Tag Archives: C# 6

C# 6 Preview: Changes in VS2015 CTP 5

C# 6 and Visual Studio 2015 are both prerelease software at the moment, and thus they are subject to change at any time.

There have indeed been some changes in C# 6 that came out in CTP 5 but which don’t seem to have been mentioned anywhere.

String interpolation

If you’ve read my original article on string interpolation, you’ll know that the syntax was expected to change. Well, that has happened, and the expected syntax is now in place. So now, you can use string interpolation to write special formatted strings as follows:

            var name = "Chuck";
            var surname = "Norris";

            string message = $"The man is {name} {surname}";

The placeholders in the curly brackets no longer require a prefixing backslash, but a dollar sign is necessary at the start of the string to allow them to be interpreted properly.

Just like before, the placeholders are not restricted to simple variables. They may contain arbitrary expressions including properties and methods:

            var numbers = new int[] { 1, 2, 3, 4, 5 };

            string message = $"There are {numbers.Length} numbers, and their average is {numbers.Average()}";

You can use format strings in placeholders. Unlike in the original implementation, they don’t need to be enclosed in quotes if they contain operators (e.g. dashes which normally represent minus signs). However you need to be a little precise with them, as any extra space after the colon (:) appears in the output:

            var dateOfBirth = DateTime.Now;
            string message = $"It's {dateOfBirth:yyyy-MM-dd}!";

using static

I’ve also written about the using static feature before, which lets you declare a static class among the using statements and then omit the class prefix when using static methods.

The syntax has changed, and you will need to prefix the static class with the keyword “static” in the declaration. This is a good thing because it eliminates the confusion between which using statements are namespaces and which are static classes.

    using static System.Console;

    class Program
    {
        static void Main(string[] args)
        {   
            WriteLine("Hello Lilly!");

            ReadLine();
        }
    }

C# 6 Preview: String Interpolation

Update 31st January 2015: The syntax for string interpolation has changed as from VS2015 CTP5, as per the example at the end of this article. Please see C# 6 Preview: Changes in VS2015 CTP 5 for the latest syntax and examples. This article remains available due to historical significance.

Visual Studio 2015 Preview was released last week, and it supercedes the CTPs of what was previously known as “Visual Studio 14”. This VS2015 pre-release comes with a new C# 6.0 feature that wasn’t in the CTPs: string interpolation. Let’s learn about this feature by looking at an example.

I’ve got this Customer class with properties for an Id (integer), FirstName, LastName, and DateOfBirth, and I’ve declared an instance as follows:

            var dateOfBirth = new DateTime(2014, 10, 12);
            var customer = new Customer(1354, "Tony", "Smith", dateOfBirth);

Now, if I want to combine the first and last names into a full name, I can use the typical string.Format():

            var fullName = string.Format("{0} {1}", customer.FirstName, customer.LastName);

But in C# 6.0, I can use string interpolation to take out the placeholders and incorporate the string formatting arguments (in this case the two properties) directly in the string:

            var fullName = "\{customer.FirstName} \{customer.LastName}";

This eliminates the need to have placeholders that match the arguments, which can be a nightmare to maintain when you have a lot of them.

Just like string.Format(), string interpolation allows you to include formatting arguments:

            var dob2 = "Customer \{customer.IdNo} was born: \{customer.DateOfBirth:"yyyy-MM-dd"}";

In the case of the date, I had to put the format string in quotes to prevent the dashes from being interpreted as minus signs.

VS2015 highlights interpolated strings such that the referenced variables are shown as such, and not as part of the string:

vs2015-string-interpolation-highlighting

The actual syntax of string interpolation is going to change. String interpolation has gone through numerous discussions (such as this, this and this), and the development team has decided to change it for the benefit of the language. Quoting the latest C# feature descriptions (PDF):

“Note: This describes the syntax that works in the Preview. However, we’ve decided to change the syntax, to even better match that of format strings. In a later release you’ll see interpolated strings written like this:”

var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old";

C# 6 Preview: Index initializers

Dictionary initializer syntax is pretty convenient, but has always been somewhat awkward to use. It doesn’t really feel like you’re working with a dictionary at all. Let’s borrow some sample code from C# Basics: Morse Code Converter Using Dictionaries, one of my early articles at Programmer’s Ranch:

            Dictionary<char, string> morse = new Dictionary<char, string>()
            {
                {'A' , ".-"},
                {'B' , "-..."},
                {'C' , "-.-."},
                {'D' , "-.."},
                {'E' , "."}
                //...
            };

C# 6 offers an alternative syntax just for the sake of making this kind of thing more intuitive:

            Dictionary<char, string> morse = new Dictionary<char, string>()
            {
                ['A'] = ".-",
                ['B'] = "-...",
                ['C'] = "-.-.",
                ['D'] = "-..",
                ['E'] = ".",
                //...
            };

For the purpose of initialising a dictionary, you can pretty much assume that the two syntaxes above are semantically, equivalent, even though that is not entirely true. Scott Allen’s What’s New in C# 6 course on Pluralsight demonstrates that the original syntax is translated into dictionary .Add() calls, while the new one is translated into index assignments.

It is also not permitted to mix the two syntaxes above.

Note: according to the official C# feature descriptions (PDF), index initializers supposedly “do not work in the current CTP”, however the above example worked just fine in Visual Studio 14 CTP 4.

C# 6 Preview: Expression-bodied members

C# 6 is expected to simplify writing properties and methods that involve a single expression. Consider this property exposing a backing field, for instance:

        private string firstName;

        public string FirstName
        {
            get
            {
                return this.firstName;
            }
        }

We may now write this as:

        private string firstName;

        public string FirstName => firstName;

And this is also quite handy for more complex properties:

        public string FullName => string.Format("{0} {1}", this.firstName, this.lastName);

It works pretty nicely with indexers, even though the C# feature descriptions (PDF) document says it shouldn’t work in the current CTP:

    public class Inventory
    {
        private string[] inventory = new string[10];

        public string this[int index] => this.inventory[index];

        public void Put(int index, string item)
        {
            this.inventory[index] = item;
        }
    }

The expression-bodied members feature gives you a pretty convenient way to write getter-only properties. However, this syntax isn’t restricted to properties alone; you can also use it with methods. The following examples are from the official C# feature descriptions (PDF):

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;

void methods, which don’t return anything, may also take advantage of this syntax. In fact, we can quite easily rewrite the Inventory class’s operations using expression-bodied methods:

    public class Inventory
    {
        private string[] inventory = new string[10];

        public string this[int index] => this.inventory[index];

        public void Put(int index, string item) => this.inventory[index] = item;
        public void RemoveAt(int index) => this.inventory[index] = null;
    }

You can appreciate how this can make classes much more concise.

C# 6 Preview: Parameterless struct Constructors

Update 20th October 2015: As Karl Fenech pointed out, this feature has been dropped in the final version of C# 6.0.

Up until C# 5, you couldn’t have a parameterless constructor in a struct. So if you try something like this:

    public struct Point
    {
        public int x;
        public int y;

        public Point()
        {
            this.x = 0;
            this.y = 0;
        }

        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

…then it’s not quite going to work:

struct-parameterless-constructors-vs2012

At the time of writing this article, using a parameterless constructor in a struct as above is now supported, but as an experimental feature. This means you need to edit your project’s .csproj file and add the Experimental language version as shown below:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <LangVersion>Experimental</LangVersion>
  </PropertyGroup>

Parameterless struct constructors still require you to initialise all members of the struct, just like any other struct constructor.

Additionally, parameterless struct constructors must be public:

struct-parameterless-constructors-vs14ctp4

The reason for this is explained in the C# Design Notes for Aug 27, 2014:

C#, VB and F# will all call an accessible parameterless constructor if they find one. If there is one, but it is not accessible, C# and VB will backfill default(T) instead. (F# will complain.)

It is problematic to have successful but different behavior of new S() depending on where you are in the code. To minimize this issue, we should make it so that explicit parameterless constructors have to be public. That way, if you want to replace the “default behavior” you do it everywhere.

C# 6 Preview: Exception filters

We already have the ability to branch our exception-handling code depending on the type of exception, by using multiple catch blocks:

            try
            {
                Console.WriteLine("Enter a number");
                string inputStr = Console.ReadLine();
                int input = Convert.ToInt32(inputStr);
                Console.WriteLine(5 / input);
            }
            catch(FormatException ex)
            {
                Console.WriteLine("Input must be a number");
            }
            catch(DivideByZeroException ex)
            {
                Console.WriteLine("Can't divide by zero");
            }
            catch(Exception ex)
            {
                Console.WriteLine("Doh");
            }

In C# 6, we will be able to filter exceptions by handling them only if a condition is true. For example, we may want special treatment for exceptions that have an InnerException:

        static void Main(string[] args)
        {
            try
            {
                throw new InvalidOperationException("Invalid operation",
                    new Exception("Justin Bieber is breathing"));
            }
            catch(Exception ex) if (ex.InnerException != null)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("  -->{0}", ex.InnerException.Message);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }

An additional benefit of exception filters is described in the C# feature descriptions (PDF):

Exception filters are preferable to catching and rethrowing because they leave the stack unharmed. If the exception later causes the stack to be dumped, you can see where it originally came from, rather than just the last place it was rethrown.

The same PDF also describes a method to take advantage of the conditional expressions used in exception filters in order to perform some action that uses but does not actually handle the exception. The description and code below are taken from that PDF.

It is also a common and accepted form of “abuse” to use exception filters for side effects; e.g. logging. They can inspect an exception “flying by” without intercepting its course. In those cases, the filter will often be a call to a false-returning helper function which executes the side effects:

private static bool Log(Exception e) { /* log it */ ; return false; }
…
try { … } catch (Exception e) if (Log(e)) {}

C# 6 Preview: The Safe Navigation Operator (?.)

The safe navigation operator, first announced and described in this blog post, has been available since the first Visual Studio 14 CTP due to its popularity in Visual Studio User Voice..

The operator, written as ?. in code, has been referred to by many names: safe navigation, null-conditional, null propagation, and conditional access are the ones I’ve come across so far.

Just to demonstrate the concept in an extremely simple manner, consider the following code:

            List<string> list = null;
            int count = list.Count;

It’s pretty obvious that if you try to run the above code, you’re going to get a NullReferenceException, because you’re trying to access the Count property of an object that is null.

Now, the example above can seem dumb because it’s pretty obvious that the list is null, but sometimes objects can come from external sources or user input, and so you have to be careful how you handle them. In this case we can work defensively by adding a null check:

            List<string> list = null;
            if (list != null)
            {
                int count = list.Count;
            }

That’s okay. But it can get pretty messy when there is a chain of references involved. Consider a binary tree, for instance.

var something = binaryTree1.LeftChild.LeftChild.Name;

If we were to write defensive conditionals for this, you effectively need a null check for each access.

            List<string> list = null;
            int? count = list?.Count;

The use of the safe navigation operator involves putting a question mark before the dot operator, as shown above. If list happens to be null (which it is in this case), then the Count property is not accessed, and null is immediately returned. Since list?.Count may return either a number or null, the count variable must now be nullable.

The safe navigation operator pays off pretty nicely when you have more complex reference accesses:

var something = binaryTree1?.LeftChild?.LeftChild?.Name;

It also works pretty nicely with the null-coalescing operator.

            List<string> list = null;
            int count = list?.Count ?? 0;

We can even use it to guard access to array elements when the array is null:

            string[] names = null;
            int length = names?[1].Length ?? 0;

…or guard access to array elements which may themselves be null:

            string[] names = new string[] { "Steve", null, "John" };
            int length = names[1]?.Length ?? 0;

The safe navigation operator is quite convenient in properties which make use of object instances. Consider the following property:

        public string SessionId
        {
            get
            {
                if (this.Session != null)
                    return this.Session.Id;
                else
                    return null;
            }
        }

We can now simplify this to:

        public string SessionId
        {
            get
            {
                return this.Session?.Id;
            }
        }

It’s also convenient to use the safe navigation operator to raise an event only if some delegate is subscribed to it. Consider an INotifyPropertyChanged implementation:

        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

You can’t just stick in a ?. before the paranthesised argument list. So the recommended way to do this is by using the Invoke() method:

        public event PropertyChangedEventHandler PropertyChanged;

        // Create the OnPropertyChanged method to raise the event 
        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            handler?.Invoke(this, new PropertyChangedEventArgs(name));
        }

The safe navigation operator isn’t going to change our lives. But it’s one of those sweet syntactic sugar features that we’ll grow to love in time.

C# 6 Preview: Autoproperty enhancements

C# 6 extends the power of autoproperties.

Up to now, if you wanted to have a read-only property, then you had two options. You could either give up on autoproperties altogether, and use a readonly backing field exposed by a property:

        private readonly string name = "Snoop";

        public string Name
        {
            get
            {
                return name;
            }
        }

Or you could use an autoproperty with a private setter, which isn’t really read-only (it could be modified somewhere in the same class), and also means you’ll have to set the value in a constructor:

        public string Name { get; private set; }

        public Dogg()
        {
            this.Name = "Snoop";
        }

Fear not! C# 6 supports autoproperty initializers…

        public string Location { get; set; } = "NYC";

…which, quite conveniently, also work for getter-only properties:

        public string Name { get; } = "Snoop";

So it is now possible to declare an autoproperty without a setter, and its backing field will be implicitly declared as readonly.

These autoproperty initializers would have worked pretty nicely with a feature called primary constructors. But since this feature has been dropped, the usefulness of getter-only autoproperty initializers is restricted to readonly properties.

It is also worth mentioning this note about mutability from the C# feature descriptions [PDF]:

“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.”

Eventually you’ll also be able to initialize getter-only autoproperties from within constructors, but at the time of writing this article, it is not yet supported in the latest CTP (Visual Studio 14 CTP4).

C# 6 Preview: await in catch and finally blocks

Up until now, you couldn’t put an await in a catch or finally block. That changes in C# 6.

I’ve got this Logger class, whose implementation is pretty trivial. This is how I’m using it in a simple WPF application’s button event handler:

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            using (var logger = new Logger())
            {
                try
                {
                    await logger.LogAsync("Executing operation...");
                }
                catch (Exception ex)
                {
                    await logger.LogAsync(ex.ToString());
                }
                finally
                {
                    await logger.FlushAsync();
                }
            }
        }

As you can see, in C# 6 you can now await asynchronous operations from within your catch and finally blocks, which is very useful in cases such as the above.

C# 6 Preview: Declaration Expressions

Note: although this feature appears to be implemented as an experimental language feature in Visual Studio 14 CTP4, the Roslyn language features page seems to indicate that it won’t be supported. In fact this post seems to confirm that declaration expressions won’t make it into the next version of .NET. Keep this in mind as you continue reading.

Update 14th April 2017: Although this feature did not make it into C# 6, it is now available as from C# 7 (released in 2017).

One of the new features in C# 6 is that we’ll be allowed to declare a variable from within an expression. The most common example of this is in the out parameter of a TryParse() call. Consider this code:

            Console.WriteLine("How old are you?");
            string input = Console.ReadLine();

            int x = 0;
            if (int.TryParse(input, out x))
                Console.WriteLine("You don't look {0}!", x);
            else
                Console.WriteLine("That doesn't sound quite right.");

            Console.ReadLine();

That x declaration is a little annoying – it wastes a line just to declare a variable so that we can get an out parameter into it. In C# 6, we can finally get rid of it:

            Console.WriteLine("How old are you?");
            string input = Console.ReadLine();

            if (int.TryParse(input, out int x))
                Console.WriteLine("You don't look {0}!", x);
            else
                Console.WriteLine("That doesn't sound quite right.");

            Console.ReadLine();

To actually get this working in Visual Studio 14 CTP4 (which is the latest at the time of writing this article), you’ll need to set the LangVersion to Experimental by editing the .csproj file in a text editor and adding the line highlighted below:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <PlatformTarget>AnyCPU</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <ErrorReport>prompt</ErrorReport>
    <WarningLevel>4</WarningLevel>
    <LangVersion>Experimental</LangVersion>
  </PropertyGroup>

Now, I particularly love this feature because I use concurrent collections a lot. And those are full of out parameters. Here’s an example using a ConcurrentDictionary:

            var dict = new ConcurrentDictionary<string, Guid>();
            bool added = dict.TryAdd("user1", Guid.NewGuid());

            bool retrieved = dict.TryGetValue("user1", out Guid user1Guid);
            Console.WriteLine(user1Guid);

            Console.ReadLine();

Now, declaration expressions are useful for more than just out parameters. In fact, if you read Scott Allen’s article on the subject, you’ll see a couple of examples of declarations within conditional and loop expressions. Below is an example of how declaration expressions may be used in a loop:

            foreach (var num in var numbers = Enumerable.Range(1, 10))
                Console.WriteLine("Processing {0} of {1}...", num, numbers.Count());

…and here’s the output of that, just so you get the idea:

Processing 1 of 10...
Processing 2 of 10...
Processing 3 of 10...
Processing 4 of 10...
Processing 5 of 10...
Processing 6 of 10...
Processing 7 of 10...
Processing 8 of 10...
Processing 9 of 10...
Processing 10 of 10...

Finally, here is an example from the Roslyn C# feature descriptions (CTP3) [PDF] which shows how declaration expressions can facilitate the use of out parameters in queries, where declarations were previously not possible:

from s in strings
select int.TryParse(s, out int i) ? i : -1;