My Three Favorite Language Features of C# 6

Created: August 22, 2015 Tagged As: .net, C#, Language Share:

With Visual Studio 2015 brings C# 6 and some new language features that makes programming faster and less error-prone. These are my three favorite new features thus far.

String.Format Replacement - String interpolation

String.Format provides the ability to create a string comprising of a literal with several tokens placed in it. For example, String.Format("There are {0} item{1}.", i, i<2?"", "s") will replace {0} with i and {1} with i<2?"", "s". As the number of tokens increases so does the chance for error are they are replaced sequentially - so not only do you need the right number of tokens, they need to be in the right order. And unfortunately, the compiler doesn't catch any of this.

C# 6 fixes this with the $ string keyword. Using it the above example would become $"There are {i} item{(i<2 ? "" : "s")}." which is more succinct, and more importantly, less prone to error as each token is inline with the string and actually processed by the compiler (and Intellisense).

I find myself using this where ever I would have used String.Format before and my code is definitely cleaner for it!

Property Initializers

When auto properties were introduced I cried a little since it made life so much easier! Now you can initialize auto properties inline with their definition - wow!

The "old old" way (before auto properties):

protected int _count = 10;
public int Count
{
    get return _count; }
    set { _count = value; }
}

The "old way (using auto property):

public int Count
{
    get;
    set;
}

public
 MyObject()
{
   this.Count = 10;
}

The "new" way (using auto property with initializer):

public int Count 
{ 
   get; 
   set; 
} = 10;

This really simplifies coding and, I think, also makes it easier to read. Not that this can be used with getter-only properties as well!

Static Class Member Referencing

One thing that has always frustrated me is constantly calling static class names like Console or Math when those classes need to be used. Apparently I was not alone as the Microsoft Language Team added a new feature just to address this issue - "using static".

using static System.Math;
using static System.Console;

In the example above, static members from both the Math and Console classes can now be called without needed to prefix them with the class name! For instance, WriteLine and Sqrt can be written just like that.

This works for any class, even your own - just make sure property / method names do not conflict.

 

For a full list of the new features, please click here.