C# 6.0 new features and .NET 4.6

Visual Studio 2015 is power packed and comes with lots of new features for developers. One of them is version 6 of C# language. Unlike previous versions, there are no major addition of features but the new features introduced in version 6 are syntactical and that’s why I bet you would pray and start counting days to use them in your projects!

First thing is, get Visual Studio 2015 from the link below and install it.
https://www.visualstudio.com/downloads/download-visual-studio-vs

Once you are all setup, you can start with a console or any windows application project targeting .NET 4.6 framework. Here I will demonstrate the new features using one simple class as follows:

public class Author
    {
         public Author()
        {
            FirstName = string.Empty;
            LastName = string.Empty;
            BookTitles = new List<string>();
            DateCreated = DateTime.UtcNow;
        }

        public string FirstName { get; set; }
         public string LastName { get; set; }
        public string FullName { get { return string.Format("{0] {1}", FirstName, LastName); } }
        public DateTime BirthDate { get; set; }
         public DateTime DateCreated { get; set; }
         public IList<string> BookTitles { get; set; }
    }

Listing 1.0 Author class

Now I will convert this class into following version which will make use of new C# 6.0 features.

public class Author
{
1. public string FirstName { get; set; } = string.Empty;
2. public string LastName { get; set; } = string.Empty;
3. public string FullName => $"{FirstName} {LastName}";
4. public DateTime BirthDate { get; set; }
5. public DateTime DateCreated { get; set; } = DateTime.UtcNow;
6. public IList<string> BookTitles { get; set; } = new List<string>();
}

Listing 1.1 Author class using C# 6.0 features

So as per Listing 1.1 let’s go through each of the new features line by line.

- Line 1, 2, 5 and 6 demonstrate usage of Auto-property initializers. To initialize property to default value, you would typically do this in constructor. Now in C# 6.0, you can do this inline.

- Line 3 shows usage of string manipulation using $ sign. For typical calculated property, you would use string concatenation or String.Format or StringBuilder to achieve the same. But now you can see the expression is quite clean and short. You can still make use of String.Format and define it like following:

public string FullName => string.Format("{0} {1}", FirstName, LastName);

Let’s add method CalculateAge to the class which will return age of the Author. If I use C# 6.0, it would be as following:

public TimeSpan CalculateAge() => DateTime.Now - BirthDate;

Listing 1.2 Lambda expression to define method body

Listing 1.2 shows usage of Lambda expression to define method body inline.

Consider the following code. You often write such code when you make Linq queries on a collection which comes from service and you want to make sure to prevent Null exception.

var list = this.GetAllAuthors();
            var author = list.FirstOrDefault(c => c.FirstName.Equals("Jay"));
            if (author != null)
            {
                var fullName = author.FullName;
            }

Now, you can write it like following.

var list = this.GetAllAuthors();
var name = list.FirstOrDefault(c => c.FirstName.Equals("Jay"))?.FullName;

Listing 1.3 Null conditional operator  

In the Listing 1.3, one thing to take care about is if your type FullName is nullable, it would set name to nullable type. In our case, it would be simply null string.

Now next new feature would be good enough to use when you are developing some wrapper or helper or utility classes for your project where you deal with any framework classes which are exposing handful of static methods. You can now use static keyword while defining namespace and it would allow access to all the static methods of that class without specifying the class name as shown in Listing 1.4.

using static System.IO.File;
var file = @"C:\Documents\ReadMe.txt";

if (!Exists(file))
{
   Create(file);
}

Listing 1.4 Static namespace

If you are good JavaScript developer, you would like the new feature that changes syntax for initializing indexed collection such as dictionary.  The following code of initializing a Dictionary object can be written as shown in code Listing 1.5.

Dictionary<int, string> valueDict = new Dictionary<int, string>
{
    {1, "Value1" },
    {2, "Value2" },
    {3, "Value3" }
};

Now in C# 6.0 it will feel much like JavaScript. Isn’t it?

Dictionary<int, string> valueDict = new Dictionary<int, string>
    {
        [1] = "Value1",
        [2] = "Value2",
        [3] = "Value3"
    };

Listing 1.5 Index initializer

If you are code ninja and code both in VB and C#, you would love addition of Exception filters in C#. What this means is, you can now filter exception based on the condition and catch block only executes when the condition is true. Listing 1.6 shows this code.
    try
{
    throw new Exception("NoDataFound");
}
catch (Exception ex) if (ex.Message == "NoDataFound")
{
    //// this will get executed.
}
catch (Exception ex) if (ex.Message == "InvalidDataFound")
{
    //// this will not
}

Listing 1.6 Exception filter

If you have worked in Windows Store apps and in .NET 4.5, you must have felt lack of using await in catch block. Often you come to a situation where you log or say send error report to service (like RayGun.io) in catch block. Now you can use it as shown in Listing 1.7.

try
{
    ReadFileFromDocuments();
}
catch (Exception)
{
    await LogService.LogAsync(ex);
}

Now it’s time for ReSharper and StyleCop to update them to adhere to this new features of C# and create rules for best practices! Happy coding!

By jay nanavati   Popularity  (2652 Views)