Login


What's New in C# 6 (Part 2)

By Jonathan Wood on 7/30/2015
Language: C#
Technology: .NET
Platform: Windows
License: CPOL
Views: 16,236
Frameworks & Libraries » .NET » General » What's New in C# 6 (Part 2)

Introduction

This article is part 2 of 2 about the new features in C# 6. If you missed Part 1, please see the article What's New in C# 6 (Part 1).

Expression-Bodied Members

Listing 1.1 shows the implementation of a typical getter-only class property.

Listing 1.1: A typical getter-only class property.

private int value;

public int ValueTimesTwo
{
    get
    {
        return value * 2;
    }
}

As you can see, there is a fair amount of syntax for such a simple property. Of course, C# programmers are used to the compactness of lambda expressions, so how about being able to use a lambda-type expression for a property?

That's exactly what expression-bodied members allow you to do. Listing 1.2 demonstrates this. Notice how much cleaner and compact the code is in comparison to Listing 1.1.

Listing 1.2: A getter-only class property implemented as an expression-bodied member.

private int value;

public int ValueTimesTwo => value * 2;

Await in catch/finally

Microsoft has admitted they had trouble wrapping their heads around how to go about implementing multi-threading with the await keyword from within a catch or finally block. As a result, this has not been supported in the past.

After implementing the await keyword, the number of requests to have this supported within exception blocks was higher than expected. Apparently they've worked it out and this is now supported in C# 6. This is demonstrated in Listing 2.1.

Listing 2.1: Using await within a catch or finally block.

public static async Task<int> TestExceptionAsync()
{
    try
    {
        // Do work here ...
    }
    catch (Exception exception)
    {
        await LogExceptionAsync(exception);
    }
    finally
    {
        await LogCompletionAsync();
    }
}

Exception Filters

Another enhancement to exception handling are exception filters. Exception filters allow you to add a condition to a catch block. The catch block is executed only if that condition is true. Otherwise, another block may be executed as appropriate.

Listing 3.1: Using exception filters.

public static async Task<int> TestExceptionAsync()
{
    bool condition = false;
    try
    {
        // Do work here ...
        condition = true;
        // Do more work here ...
    }
    catch (Exception exception) if (condition)
    {
        // This block is executed only if condition is true
    }
}

Of course, the code in Listing 3.1 could simply check if condition is true within the catch block. But if it was not, no other catch blocks would execute. The catch block would have already been entered and would continue executing normally. By placing this filter outside of the block this way, execution may continue on to other catch blocks as appropriate if the condition is not true.

String Interpolation

An efficient way to construct a string with variables is to use the String.Format() method as shown in Listing 4.1.

Listing 4.1: Using String.Format() to format a string.

string first = "Bob";
string last = "Smith";
int age = 30;

string s = String.Format("{0} {1} is {2} years old.", first, last, age);

This approach works well but there are a few downsides. For one thing, you have to be careful to get things in the right order or you won't get the right result at all. You also have to be careful to have the right number of arguments to match the placeholder numbers within the format string. Also, it might be nice if it required a little less typing.

String interpolation provides a different approach to formatting a string. By prefixing the string with the dollar sign ($), you can use curly braces to insert variables directly within the string. This is demonstrated in Listing 4.2.

Listing 4.2: Using string interpolation to format a string.

string first = "Bob";
string last = "Smith";
int age = 30;

string s = string s = $"{first} {last} is {age} years old.";

For me personally, I sort of prefer the String.Format() syntax. Perhaps that's just what I'm used to. Either way, we now have another choice in how we can format a string.

Using Static Members

When accessing static member of a class, you reference the class name, followed by a dot, followed by the static member name. For example, Listing 5.1 demonstrates calling the static System.Console.WriteLine() method.

Listing 5.1: Accessing a static member.

using System;

class Test
{
    public WriteMessage(string message)
    {
        Console.WriteLine(message);
    }
}

This works fine, but if you need to access WriteLine() many times in your code, it does add up to quite a bit of extra typing.

C# 6 adds a shortcut using the new using static directive. Normally, the using directive can only reference namespaces. But when you add the static keyword, you can also reference a type. Listing 5.2 demonstrates how to use a using static directive that references the Console class. Note that the code no longer needs to reference the Console class in order to access the static WriteLine() method.

Listing 5.2: Accessing a static member with a using static directive.

using System;
using static System.Console;

class Test
{
    public WriteMessage(string message)
    {
        WriteLine(message);   // No need to reference Console here
    }
}

Of course, this technique works on your own types in addition to those defined in the .NET runtimes. This could easily get out of hand if you used it for many classes. There are likely to be naming collisions. But for a static member that you access often, it can reduce typing and make your code a little cleaner.

Dictionary Initializers

Dictionary initializers provide a new syntax that can be used to initialize dictionary items. Listing 6.1 illustrates the new syntax.

Listing 6.1: Using the new dictionary initializer to initialize a dictionary collection.

Dictionary<string, int> lookup = new Dictionary<string, int>
{
    ["abc"] = 123,
    ["def"] = 456
};

To be honest, I'm not sure I see much value in this addition. The same thing could be achieved using the syntax { "abc", 123 } for each item, and I'm not sure the new syntax is any better.

But there are now two different ways to initialize a dictionary. There are indications that this change is actually related to some other changes to C# that we may see at a later date.

Conclusion

As you can see, C# is anything but static. I'm pretty excited about some of the new features. There were additional features that didn't make the C# 6.0 release and a lot of additional features planned for the future.

It will be interesting to see how the language develops.

End-User License

Use of this article and any related source code or other files is governed by the terms and conditions of The Code Project Open License.

Author Information

Jonathan Wood

I'm a software/website developer working out of the greater Salt Lake City area in Utah. I've developed many websites including Black Belt Coder, Insider Articles, and others.