Updated Csharp 6.0 features in RTM VS2015

There are plenty of Blogs and article already posted about the C# 6.0 new features. But I observed there are some changes from the features in the preview and newly shipped with Visual Studio 2015 RTM (Of course some improvements based feedback from Preview). In this blog post, I’m trying to address those changes as well as describing new features altogether.
Below is the list of enhancement delivered in the RTM version of CSharp 6.0(Excluding VB enhancements which were mentioned in the source, Also I have added quick samples to illustrate the enhancements):

Feature Example
Auto-property initializers public int X { get; set; } = x;
Read-only auto-properties public int Y { get; } = y;
Constructor assignment to getter-only autoprops public DemoClass{
   Y = 15;
Static imports using static System.Console; … Write(4);
Index initializer > new JObject { ["x"] = 3 }
> var numbers = new Dictionary<int, string> {
    [7] = "seven",
    [9] = "nine",
    [13] = "thirteen"
Await in catch/finally try … catch { await … } finally { await … }
Exception filters catch(E e) when (e.Count > 5) { … }
Partial interfaces Partial Interface I1
Multiline string literals "Hello<newline>World"
Expression-bodied members public double Dist => Sqrt(X * X + Y * Y);
Null-conditional operators customer?.Orders?[5]
String interpolation $"{p.Name} is {p.Age} years old."
nameof operator string s = nameof(Console.Write);
#pragma #Disable Warning BC40008
Read-write props can implement read-only interface properties <"In my TODO items"> 
#Region inside methods     public void TestMethod()
        #region MyRegion

CRef and parameter name     /// <summary>
    /// Initialize with <see cref="Program(DateTime)
    /// </summary>
    public Program(DateTime timestamp)

Extension Add in collection initializers See the explained example below
Improved overload resolution <"In my TODO items"> 

Most of the features enhancements mentioned above are self explanatory, So I’ll be explaining only interesting ones those need some explanation.

Properties Enhancements

We have couple of enhancement in Auto properties. With new enhancements the compiler generated generated the required code and save some developers time. Now the properties can do:

public class Person
    // Readonly properties are not allowed to be initialized in Constructor
    public int Id { get; }
    public Person()
        // Initialzing the readonly property.
        this.Id = -1;
    // Initialize the property right at the declaration
    public string Name { get; set; } = "Jhon Doe";
    public int Age { get; set; }
    public string Title { get; set; }

Note: Static properties are not allowed to have constructor initialization.

Static Imports and Extension methods

Now the C# allows to import the static members of another class without using the class name. So they can be used directly into another class. This feature is extended to include the Extension methods. Also the Improvement was done with Using now one must use Static keyword to import the static members.

using System.Text;
using System.Threading.Tasks;
using static System.Console;
using static System.Linq.Enumerable;
public class Demo
    public void Print()
        var cultures = new string[] { null, "en-NZ", "en-US", "en-AU", "en-GB" };
        Write("The static methods are directly available.");
        // Here Range() is static so only simple static methods are allowed to use. 
        // Extensions are static 
        // but they are not be allowed to use directly. 
        // This is taken care of very carefully to keep the 
        // separation in these two types of features.
        WriteLine(Range(0, 10).Where(x => x % 2 == 0));

Extension Add method for Collection Initializers

This looks interesting but this feature was already there in VB.Net surely it was brought back home to C#. It could be value added where Generic collection are need to be initialized with complex types. Here’s a sample how it works:
E.g. below is a simple entity representing a complex type (Let’s assume)

public class Person
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Title { get; set; }

Now C#6.0 allows use to write an extension Add method for a Collection: E.g.

public static class Extensions
    public static void Add(this List<Person> source, int id,  string name, int age, string title)
        source.Add(new Person {
            Id = id,
            Name = name,
            Title = title,
            Age = age

If we want to use this collection of type Person in the code then collection initializer would lesser work:

List<Person> List = new List<Person>()
    { 1, "Ramesh", 22, "Mr." },
    { 2, "Julia", 24, "Ms" },
    { 3, "Paula", 12, "Mrs." },

This might not look like a big change but surely going to add some values in some cases e.g. Unit tests where collection are need to be created for Fake data.
I hope most of us will enjoying these feature though it will take some time to pick them as handy feature. Those which are marked as “TODO” item, I’ll be working on exploring them and may be writing about them in upcoming blog post.

No comments:

Post a Comment