Playing with C# 6 features

C# 6 has got nothing major coming like LINQ or async/await in past instead it has got several small enhancements which actually helps you clean up your code and get ride of boilerplate code. In this post, I am going to share some of the code snippets I wrote to explore new features in C# 6.

This post is written using VS 2015 CTP6, so the actual specs may vary by the time of final release. If you want to quickly get hands on Visual Studio 2015 CTPs without setting up environment, you can create virtual machine from gallery in Azure

String interpolation:
Methods like string.Format in C# provides great functionality to construct strings using placeholders. However that approach is a bit confusing and error-prone. C# 6 introduces a new way to use variable placeholders directly in string instead of number based placeholders by placing ‘$’ symbol before the string. This makes code a lot more readable.

public static void StringInterpolationEnhancements()
  string name = "Adil";
  DateTime date = new DateTime(2015, 03, 13, 10, 15, 0);
  int versionYear = 2015;
  // Previously in C# 5
  WriteLine(string.Format("This code was written by {0} on {1} using Visual Studio {2}", name, date, versionYear));

  // In C# 6
  WriteLine(string.Format($"This code was written by {name} on {date} using Visual Studio {versionYear}"));
  // In fact you don't need to call string.format 
  WriteLine($"This code was written by {name} on {date} using Visual Studio {versionYear}");

  // This is especially handy when you add more parameters in string format over the time and the order get confusing
  string content = "blog";
  WriteLine(string.Format("This {3} was written by {0} on {1} using Visual Studio {2}", name, date, versionYear, content));

  WriteLine($"This {content} was written by {name} on {date} using Visual Studio {versionYear}");

Using static members:
A lot of time you have a class with bunch of static methods and you have to call them via class. e.g.

using static System.Console;
//Previously in C# 5
Console.WriteLine("This is how to use static classes");
// In C# 6 by adding namespace using static System.Console;
WriteLine("Just call the static method directly"); 

This was one of the feature I liked in Java and its now added in C# as well although Java don’t have many other goodies from C#.

Null propagation:
This one is interesting. Often we have methods with more statements to do null checks then actually intent of method. C# 6 introduces a new null propagation operator (?.) This would automatically check if the left hand side is not null then it uses property of that object.

public void DisplayStudent(Student student)
  // Previously in C# 5
  if (student != null)

public void DisplayStudentInCSharp6(Student student)
  //In C# 6

If you want to work with primitive type because C# already has nullable primitives, you can write something like

int? age = student?.Age;

This is especially handy in firing events because you don’t have to do a thread safe null check

event EventHandler OnNetworkChange;
void RaiseNetworkChange()
    OnNetworkChange?.Invoke(this, new EventArgs());

However I was looking for cases when we have to add null checks before iterating on a collection but I don’t think it works in foreach statement but may be it’s good idea to check language specs or ask this question to language team. Do you know about it, reader?

// can I say something like student?.Courses?.GetEnumberable()
foreach (var course in student.Courses)

Expression bodied members:
For method having single return statement or properties with a getter having single return statement, C#6 lets you implement a method with single expression, like we use to do define lamba expressions.

//Instead of 
public override string ToString()
  return string.Format("Value : {0}, value};

// We can define expression in C# 6
public override string ToString() => $"Value : {value}";

Dictionary Initializers:
C# 3.0 introduces concept of object intializers where you can initialize properties of object like

Student student = new Student { Name = "Adil" };

However if you want to initialize index or dictionary you have to initialize say dictionary first and set value at index in separate statement but not any more

Dictionary<string, int> dictionary = new Dictionary<string, int> {["Year"] = 2015,["Month"] = 03,["Day"] = 15 };

Other enhancements:
There are few other enhancements in the language as well.
– Getter only auto properties
– Constructor assignment for getter only properties
– Auto properties initializers
– Catching exception with filters
– await in catch/finally block
– nameof operator

public class OtherEnhancements
    // A getter only property with readyonly backing field
    public int DemoInt { get; }

    // An auto property intialized with default value
    public string DemoString { get; set; } = "Demo";

    public OtherEnhancements()
        // Assignment in constructor for getter only field behaves like readonly field
        this.DemoInt = 100;

    public void DemoMethod()
            // Some code to capable to raise FileNotFoundException
        // catch exception with filter to handle only for particular file 
        catch (System.IO.FileNotFoundException exception) when (exception.FileName == "abc.txt")
            // In previous version of C#, you have to check it inside
            // and then re throw which would result in losing exception data

That’s all for this post. The complete sample for above code snippets is available at Github Gist.

Have you tried new features yet? any interesting scenario you would like to share in comments?