As most of you know, or some may not, the new 6.0 versión of C# is baking, and will be out shortly. This new version codenamed “Roslyn” is part of the new Microsoft’s “Opennes” change, and so, can be found as open source at Github.

I’ve been reading articles about the new features it’s gonna bring for some time now from official sites and from people testing the Visual Studio 2015 Preview. I link to the sources at the end of this article.

Some articles point to their favorite feature/s, while some other other try to get a global view. In this article, I’ll try myself to make a compilation of all (or most) of these new features, and, as part of my contribution, will also try to give some “real life” uses of them, so you can judge for yourself if they will or won’t be useful for you.

If you just want to do it the fast way, there’s a PDF “official” file linked from github’s project Roslyn site and you can download it from this link, but I would like you to keep on reading… this one is full of examples!

New features confirmed in C# 6.0 Roslyn

This are the features planned to release with C# 6.0

And this ones are Some features have been cut as Oct 2014 (source):

One by One

I’m gonna do a fast-pass at all the new additions, including a real-life example, and my personal evaluation of its utility.

Initializers in auto-properties

When you have properties that must be initialized by default in your class, you have to do this:

private string _myProperty = "Default value";
public string MyProperty { 
   get { return _myProperty; } 
   set { _myProperty = value; } 

or this:

public class MyClass {
   public string MyProperty { get; set; }

   public MyClass() {
      MyProperty = "Default value";

With C# 6.0, you can add default values to your auto-properties this way:

public string MyProperty { get; set; } = "Default value";

Level of usefulness: high

Static using

When we use a static class for several calls to its methods, the code can be a little messy like this, where the class name almost hides what we are doing:
Let’s look at how things must be done with the current version of C#:

private void LogEverywhere(string logString) {
   if (MyMagnificentStaticLogger.MustLogToDB 
        && MyMagnificentStaticLogger.IsConnectedToDB())
   if (MyMagnificentStaticLogger.MustLogToCloud
        && MyMagnificentStaticLogger.IsConnectedToCloud())

With the new static usings in C# 6.0, that could look much more readable:

using MyNamespace.MyMagnificentStaticLogger; // this is a class!

private void LogEverywhere(string logString) {
   if (MustLogToDB && IsConnectedToDB())
   if (MustLogToCloud && IsConnectedToCloud())

Phew! a little more readable, isn’t it?

Level of usefulness: medium

String interpolation

String interpolation will make easier mixing strings with values, as you can do in string.Format but without the need to call any method, and making the string much more readable. Where you now do this:

return string.Format("You have {0} messages. First at {1}, last at {2}", 
                   msgCount, firstMsg, lastMsg);

With C# 6.0 you will do something like this:

return $"You have {msgCount} messages. First at {firstMsg}, last at {lastMsg}";

The final syntax is not yet definitive, but it will be similar to this example.
Updated 02/02: The last CTP Preview has changed the string interpolation syntax. Now we must use the $ prefix in the string and it’s not necessary the starting backslash.

Level of usefulness: medium

await in catch and finally

Nowadays lots of new applications work in multi-threaded mode and make use of C# 5.0 await and async keywords for asynchronous methods. One of the caveats of the C# 5.0 implementation was that the await keyword wasn’t supported in catch nor finally block, forcing you to do funky things like this:

string result = null;
bool gotResult;
Exception ex;
try {
  result = await new ApiClient().GetContentAsync(new Uri( ""));
  gotResult = true;
catch (Exception ex) {
  gotResult = false;

if (!gotResult)
  await LogClass.WriteError(ex);

return result;

With C# 6.0, await keyword is finally allowed in catch and finally blocks, and your code will look much more elegant:

try {
   return await new ApiClient().GetContentAsync(new Uri(""));
catch (Exception ex) {
   await LogClass.WriteError(ex);
   return null;

Level of usefulness: high

Null conditional operator

One of my most awaited new features. I’m really tired of things like this:

if (Invoice != null 
     && Invoice.Customer != null 
     && Invoice.Customer.Address != null
     && Invoice.Customer.Address.Zip == ZIP_TO_CHECK) {

Now you can avoid having to check all the parent objects for null using the new null conditional operator ?. doing this:

if (Invoice?.Customer?.Address?.Zip == ZIP_TO_CHECK) {

Woah! now this is saving code!

Level of usefulness: high

nameof expression

Another nice feature. Sometimes you need to work with identifier names as strings. The problem is that passing them as “magic strings” is not a recommended practice:

var label = myReflectionObj.GetLabelFor("MyPropertyName");

The problem with this approach is that using the constant string “MyPropertyName”, though it will compile without problems, the app will fail if I change the name of the property and forget to change the string in this call.

In C# 6.0 we can use nameof for this:

var label = myReflectionObj.GetLabelFor(nameof(myObj.MyPropertyName));

This is refactor-proof. When you refactor the property name elsewhere, this call will be refactored as well.

Level of usefulness: medium

Use of IEnumerable<> instead of params[]

I use the params[] keyword in my methods many times, when I want a variable number or parameters passed to it. In C# 6.0, you can define that parameters as IEnumerable<> instead. This will allow you take profit of lazy resolution of the collection.

Let’s see an example. In this method SelectByName we take an action to perform on each of the candidates array. When we make the call, we are getting all entities from DB in a IEnumerable, so nothing is read yet. But when I call the method, I must convert them with a .ToArray() call that will take ALL the DB records.

public void SelectByName(string partialName, Action<MyEntity> action, params MyEntity[] candidates) 
    candidates.Where(c => c.Name.StartsWith(partialName)).ToList().ForEach(action);

IEnumerable<MyEntity> allEntities = MyDB.GetAllEntities();
new Test().MarkAllA("Adams", t => { t.Selected = true; }, allEntities.ToArray());

With C# 6.0 I can keep the lazy chain until the moment I need, so I will only get entities with their name starting with “Adams” read from the DB.

public void SelectByName(string partialName, Action<MyEntity> action, params IEnumerable<MyEntity> candidates) 
    candidates.Where(c => c.Name.StartsWith(partialName)).ToList().ForEach(action);

IEnumerable<MyEntity> allEntities = MyDB.GetAllEntities();
new Test().MarkAllA("Adams", t => { t.Selected = true; }, allEntities);

Level of usefulness: medium

Event initializers

With the new 6.0 version, you will be able to initialize your event handlers as any other property too:

var b = new MyClass {
          Id = "ABC",
          OnChange += myClassOnChange

Level of usefulness: low

Functionalities dropped for this version

According to this post, some of the funcionalities that C# 6.0 was going to bring have been dropped from the next release. Some of them are the following ones:

Property and function declaration expressions

Too bad. This was one of my favs! Imagine if instead of doing this:

public string FormattedDate {
    get {
           return string.Format("{0:d}",this.TheDate);

You could do this:

public string FormattedDate => string.Format("{0:d}",this.TheDate);

Nifty, huh? We’ll have to wait for future releases of C# for this.

Primary constructors

This feature would allow us avoid creating constructors to assign initial property values.

Instead of this:

public class MyClass {
   private string _field1;

   public MyClass(string field1) {
      _field1 = field;

We could do this:

public class MyClass(string field1) {
   private string _field1 = field;

I find this one a little odd. I prefer the current implementation of constructors.

Indexed members and element initializers

Initializers for structures had been revamped for this version, but finally they were taken out too and will stay as they are.

The current way to initialize a collection is this one:

private Collection<int,string> myCollection =
     new Collection<int,string> {
         { 0, "Element Zero" },
         { 1, "Element One" }

The new propesed syntax was something like:

private Collection<int,string> myCollection =
     new Collection<int,string> {
         [0] = "Element Zero",
         [1] = "Element One"

Not much of a change. Nothing to worry for being cut.


To compile this article, I took ideas and information from the following sites:

Thanks and credits go for all the authors!

Thank you!

More stuff coming in short! Keep connected to my blog!

Follow me