With Visual Studio 2015 comes C# 6.0. The team at Microsoft put a whole lot of effort into the Roslyn compiler this time around and the language features are primarily syntactic sugar, but they are still extremely welcome.

The Null-Conditional Operator

Here is a small piece of code that I inherited recently.  It has a very simple task, get the client’s postcode or return ‘unknown’

how much nicer it becomes when we use the new null conditional operator

Note that the type of client?.Office?.Address?.PostCode is nullable String.

This isn’t restricted to properties, the following method can also be refactored

which is expressed more simply as

Nameof Expressions

When we have methods that expect non null properties we might typically see code like this

Notice here that the method refers to client affiliation and the property it returns is ‘MemberParty ‘. Not a very ubiquitous approach.

When we refactor to use affiliation however, the following occurs

Aargh, the dreaded magic string has caught us out.  C# 6.0 to the rescue

Now we have strongly typed properties and safe refactoring. Not a massive advance but something that has caught me out many times over the years.

Expression bodied properties and functions

Let’s say we have the following code

we can now rewrite this as

Note that these are not lambda expressions, they are just syntactic sugar intended to simplify your code and make it more readable.

String Interpolation

even better, we can change this to

Much more readable!

Also if we wanted to override the ToString method for this class, we might use several new features together in the following way

These are a few of the new language features. Like I said at the start, most of the effort this time around went into Roslyn but I really appreciate that the subtle changes they did make add to the beauty of the language.


Commenting area

  1. Superb!!

Leave a Reply
