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;

C# 6 Preview: using static

Update 31st January 2015: The syntax for using static has changed as from VS2015 CTP5. Please see C# 6 Preview: Changes in VS2015 CTP 5 for the latest syntax and examples. This article remains available due to historical significance.

Take a look at this little VB .NET program:

Module Module1

    Sub Main()

        Console.WriteLine("Hello world!")
        Console.ReadLine()

    End Sub

End Module

In VB .NET, you can take the Console static class name out of there and put it in the imports:

Imports System.Console

Module Module1

    Sub Main()

        WriteLine("Hello world!")
        ReadLine()

    End Sub

End Module

In fact, that feature works for any static class. And now, this feature is being added to C# starting from version 6. Let’s see the same example in C#. This is as you would write it in C# 5:

using System;

namespace UsingStaticHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello world!");
            Console.ReadLine();
        }
    }
}

And this is how it looks like with the new static using feature in C# 6:

using System.Console;

namespace UsingStaticHelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello world!");
            ReadLine();
        }
    }
}

Although most examples I’ve seen use this kind of scenario, I don’t think it’s a very good example of where this feature is useful. In fact, by extracting the static class name from the code that uses it, we’re reducing readability, and we’re also introducing the risk of ambiguity with other static classes that define the same method names. In this case we can’t add a static using for System.Diagnostics.Trace (which also has a WriteLine() method), but it’s quite easy to write a static Logger class that also defines a WriteLine() method, and that can be problematic.

However, the static using feature can be very useful in code that uses static methods heavily. A good example is mathematical calculations. Consider this code:

using System;

namespace UsingStaticMath
{
    class Program
    {
        static double CalculateSomething(double angle)
        {
            var numerator = Math.Sin(angle) * Math.Sin(angle) + Math.Cos(angle);
            var denominator = 1 + Math.Sqrt(Math.Sin(angle) + Math.Pow(Math.Cos(angle), 3));

            return Math.Pow(numerator / denominator, 2);
        }

        static void Main(string[] args)
        {
            var result = CalculateSomething(Math.PI / 2);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

We can make it a whole lot more concise by introducing the using static:

using System;
using System.Math;

namespace UsingStaticMath
{
    class Program
    {
        static double CalculateSomething(double angle)
        {
            var numerator = Sin(angle) * Sin(angle) + Cos(angle);
            var denominator = 1 + Sqrt(Sin(angle) + Pow(Cos(angle), 3));

            return Pow(numerator / denominator, 2);
        }

        static void Main(string[] args)
        {
            var result = CalculateSomething(PI / 2);

            Console.WriteLine(result);
            Console.ReadLine();
        }
    }
}

In this case, when you read the code, it’s pretty obvious that Sin(), Cos(), Pow() and Sqrt() are mathematical functions, and it’s also very unlikely that there will be an ambiguity.

So in summary, the using static feature can be useful in some scenarios and disruptive in others. Use it wisely.

C# 6 Preview: nameof expressions

One of the new features in C# 6 is the new nameof operator. This will give you the name of a variable or type name, for instance nameof(id) gives you “id”. It’s a very simple feature. Let’s see a couple of examples where it is useful.

The simplest example is when checking whether arguments are null. I’ve got this simple Person class:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            if (firstName == null)
                throw new ArgumentNullException("firstName");
            if (lastName == null)
                throw new ArgumentNullException("lastName");

            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

Notice how I’m passing magic strings into the ArgumentNullExceptions. If I rename the arguments, then I must remember to update the magic strings as well.

Let us now take advantage of the new nameof() operator:

    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

        public Person(string firstName, string lastName)
        {
            if (firstName == null)
                throw new ArgumentNullException(nameof(firstName));
            if (lastName == null)
                throw new ArgumentNullException(nameof(lastName));

            this.FirstName = firstName;
            this.LastName = lastName;
        }
    }

It’s evident that with this change, if you rename the arguments, you will have to rename them throughout, or you will get a compiler error. No more magic strings.

Another scenario where this is really useful is when you are dealing with NotifyPropertyChanged in a WPF application. After implementing INotifyPropertyChanged in my ViewModel, I added the following property with a backing field to facilitate data binding:

        private string currentTime;

        public string CurrentTime
        {
            get
            {
                return this.currentTime;
            }
            set
            {
                this.currentTime = value;
                this.OnPropertyChanged("CurrentTime");
            }
        }

Here we have the same problem as before: we are using magic strings, and that can be problematic especially if we refactor our property and forget to update the property name in the string. Over the years, MVVM library developers have come up with various ways to mitigate this unpleasant scenario, including passing backing fields as ref parameters when raising the PropertyChanged event, using CallerMemberName, or using expression trees to pass in the property itself. nameof() again makes things a lot easier, as shown below. Even better, it is evaluated at compile-time, so there is no performance penalty associated with its use.

        private string currentTime;

        public string CurrentTime
        {
            get
            {
                return this.currentTime;
            }
            set
            {
                this.currentTime = value;
                this.OnPropertyChanged(nameof(CurrentTime));
            }
        }