What’s new (and cool) in C# 6?

Many of the improvements in C# 6 are based around Rosyln, rebuilding the compiler and making it much easier to write Visual Studio plugins and doing fancy compilation in our own applications. This is all very exciting stuff but it doesn’t really impact me day to day. There are however two little features which I am using every day and have already slipped into my standard syntax.

The Null Conditional Operator

The Null Conditional Operator is game changing. Last year we’d have to perform a series of null checks to ensure that we weren’t going to receive a NullReferenceException when accessing the child properties of an object.


if(user != null && user.Communication != null && user.Communication.PhoneNumber != null)

{

  user.Communication.PhoneNumber.Call();

}

However with the introduction of the ?. operator we can do this all in a single line.


user?.Communication?.PhoneNumber?.Call();

If the user has both a Communication object and a PhoneNumber then call them.

This becomes even more powerful when combined with our old friend the ?? operator.


var numberToCall = user?.Communication?.PhoneNumber ?? DEFAULT_CONTACT_NUMBER;

Now if user or Communication are null instead of throwing a NullReferenceException they will evaluate as null. Now if either user, Communication or PhoneNumber are null the entire statement will return the DEFAULT_CONTACT_NUMBER instead.

String Interpolation

The new String Interpolation change is so simple but I’ve found myself using it almost exclusively since it became available.

In the past we’d write


var myMessage = string.Format("Welcome back {0}", user.Salutation);

This was fine, perhaps a little clunky when you had a lot of stings to merge in but we were happy. That was until I discovered the new C# 6 String Interpolation!


var myMessage = $"Welcome back {user.Salutation}";

Not only is this more concise, but it also eliminates the frustration we’ve all experienced when mixing up the position of the arguments.

Two simple changes, two huge reasons to use C# 6 now!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s