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.