Five C# 6.0 New Features to Look Forward To.

C# 6.0 new featuresWith Visual Studio 2015 due to ship this month, it seems like a good time to consider how C# 6.0 is going to make our professional lives just that little bit easier.

C# 6 is more evolution then revolution. It’s about smoothing off some of the rough edges of the language. So there’s something for everyone.  Below are 5 of my favorite C# 6.0 new features.

Null-conditional Operator

This is one of my favorite C# 6.0 new feature. I’m always having to write code like-

return improvement != null ? (double?)improvement.Percentage : null;

…and I don’t care for it.

In C# 6 this becomes

return improvement?.Percentage;

Much cleaner.

The null-conditional operator returns null, short-circuiting evaluation, if the instance before it is null. Otherwise, evaluation continues on to the next part of the expression.

It can be also used in more complex statements.


result.Markets = this.Event.Markets != null ? this.Event.Markets.
    Select(x => x.CreateModel()).ToList() : null;

becomes

result.Markets = this.Event.Markets?.Select(x => x.CreateModel()).ToList();

Null-conditional operators can also be chained.

result.Markets = this.Event?.Markets?.Select(x => x.CreateModel()).ToList();

Objective C and Swift have similar features so I’m pre-sold.

String Interpolation

String interpolation is another welcome addition. While string.Format is powerful enough (…you’re not using string concatenation are you?…) having to line up the {n} placeholders with the arguments can be a bit of a drag.

Using string.Format my code is

return string.Format("{0} {1}", this.FirstName, this.LastName);

With string interpolation it becomes

return "\{this.FirstName} \{this.LastName}";

If I want to switch the values around, I can do this easily using both approaches. However, the string.Format example becomes

return string.Format("{1} {0}", this.FirstName, this.LastName);

I find it difficult to reason about code like that—especially when the number of parameters increases. Of course, I could switch the placeholders and the parameters, but that’s the kind of thing that grates.

You can even interpolate expressions.

Console.Writeline("\{x} squared is \{x * x}");

Using Scala made me realise how much I prefer string interpolation over string.Format. I’m already a convert.

Auto-property Initializers

Initializing properties in the constructors never seems particularly clean. It would be better to keep the initialization with the definition. As of C# 6 this is now possible.

The syntax is pretty much the same as when initializing fields.

public double Score { get; set; } = 100.0;

The nameof Operator

The nameof operator returns the name of an identifier. This is useful in logging. I have (Log4Net) code like this in my applications

Log.DebugFormat("price = {0}", price);

This is OK until I refactor price to be cost. Then my logs start to get confusing.

Log.DebugFormat("price = {0}", cost);

nameof saves the day.

Log.DebugFormat("{0} = {1}", nameof(cost), cost);

Now I can refactor my heart out and the logs stay true. (NB. I really wanted to use string interpolation there.)

Dictionary Initializers

When I’m initializing dictionaries I write code such as

var countries = new Dictionary<String, string>
                    {
                        { "AF", "Afghanistan" },
                        { "AX", "Åland Islands" },
                        { "AL", "Albania" },
                        ...
                        { "ZW", "Zimbabwe" }
                    };

This doesn’t really make it clear that I’m are defining a set of key/value pairs. In C# 6, this becomes

var countries = new Dictionary<String, string>
                    {
                        $AF = "Afghanistan",
                        $AX = "Åland Islands",
                        $AL = "Albania",
                        ...
                        $ZW  = "Zimbabwe"
                    };

The intent is now clearer.

To retrieve a value from the dictionary, we use

var afghanistanName = countries$AF;

Summary

I’ve only covered a few of the improvements coming in C# 6—the ones that I’ve been waiting for based on experiences with other languages. Of course, these new features will not always be appropriate, but, where they are, they’ll produce cleaner code. Don’t be shy.

If you want to learn more about C# in general, the following Learning Tree courses may be of interest

image sources

  • C# 6.0 new features: Andrew Tait

Type to search blog.learningtree.com

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.