Microsoft & .NETTop 10 C# 6.0 Language Features

Top 10 C# 6.0 Language Features

In this article, I am going to list my top 10 features that are expected to be released with C# 6. Currently, C# 6 is available with Visual Studio 2015 Preview for developers to explore. I have used the CTP version 4 of the Visual Studio VNext to create the source code samples for this article.

10. Expression Bodied Methods

How many times have you had to write a method just for one line of code? Now, with C# 6 you can simply create an expression bodied member with only the expression and without the curly braces or explicit returns.

class Employee
{
   // Method with only the expression
   public static int
      CalculateMonthlyPay(int dailyWage)
      => dailyWage * 30;
}

9. ?—Conditional Access Operator

In earlier versions of the C# language, you always had to write the explicit if condition NULL checks before using an object or its property, as shown below.

private void GetMiddleName(Employee employee)
{
   string employeeMiddleName = "N/A";

   if (employee != null && employee.EmployeeProfile
      != null)
      employeeMiddleName =
         employee.EmployeeProfile.MiddleName;
}

The same can be converted into a one-liner by using the Conditional Access Operator in C# 6.

private void GetMiddleName(Employee employee)
{
   string employeeMiddleName =
      employee?.EmployeeProfile?.MiddleName ?? "N/A";
}

Notice the default value provided on the same line of code.

8. Auto-Property Initializers

With the Auto-Property initialization feature, the developer can initialize properties without using a private set or the need for a local variable. Following is the sample source code.

class PeopleManager
{
   public List<string> Roles { get; } =
      new List<string>() { "Employee", "Managerial"};
}

7. Primary Constructor

Primary Constructor is a feature in which you are allowed to pass the constructor parameters at the class declaration level instead of writing a separate constructor. The scope of the primary constructor parameters values is class level and will be available only at the time of class initialization. It comes to good use when it is used with the Auto-Property initializers.

// Primary constructor
class Basket(string item, int price)
{
   // Using primary constructor parameter values
   // to do auto property initialization.
   public string Item { get; } = item;
   public int Price { get; } = price;
}

6. OUT Parameter Declaration During Method Call

This is one of my favorites because I was feeling something not good about the separate declaration of the OUT parameter before the method call. This feature allows you to declare the OUT parameter during the method call, as shown below.

public bool ConvertToIntegerAndCheckForGreaterThan10
   (string value)
{
   if (int.TryParse(value, out int convertedValue)
      && convertedValue > 10)
   {
      return true;
   }

   return false;
}

Note that the same out parameter is used in the consequent IF condition expression.

5. Await in the Catch Block

This is an important non-syntactic enhancement that will be available in C# 6. The await keyword can be called inside the catch and finally blocks. This opens up the way to perform an async exception handling or fallback process in case an exception happened during an async process call.

public async void Process()
{
   try
   {
      Processor processor = new Processor();
      await processor.ProccessAsync();
   }
   catch (Exception exception)
   {
      ExceptionLogger logger = new ExceptionLogger();
      // Catch operation also can be aync now!!
      await logger.HandleExceptionAsync(exception);
   }
}

4. Exception Filters

Exceptions can be filtered in the catch blocks with ease and cleanly with C# 6. Following is a sample source code where the intention is to handle all Exceptions except the SqlException type.

public async void Process()
{
   try
   {
      DataProcessor processor = ne
   }
   // Catches and handles only non sql exceptions
   catch (Exception exception) if(exception.GetType()
      != typeof(SqlException))
   {
      ExceptionLogger logger = new ExceptionLogger();
      logger.HandleException(exception);
   }
}

3. Using <StaticClass> Is Allowed

This feature is something to make your code less cluttered and will reduce duplications. As with the namespaces, you can include a static class in the using statement similar to a namespace.

using System;
// A static class inclusion
using System.Console;

namespace CSharp6Demo
{
   class Program
   {
      static void Main(string[] args)
      {
         WriteLine("Console. is not required
            as it is included in the usings!");
      }
   }
}

2. String Interpolation

It can be looked at as an improvement to the String.Format functionality where, instead of the place holders, you can directly mention the string expressions or variables.

static void Main(string[] args)
{
   string name = "Robert";
   string car = "Audi";
   WriteLine("{name}'s favourite car is
      {car}!");
}

1. Roslyn—A New Compiler for C# and VB

Roslyn is the compiler for the C# 6 language; it has quite a bit of compiler improvements and, importantly, it is open source. Compiler Roslyn is also available as a service, in other words a “compiler as a service” because you can use the Roslyn API libraries to extend. This is just a scratch on the surface of Roslyn. I will leave it to the readers to explore it more.

I hope this article gives a highlight of the features that can be expected with the actual RTM of C# 6. Altshough it doesn’t seem to have any breaking features, it definitely has the improvements to make your code look cleaner, better, and easier. Integration of the Roslyn compiler is definitely in the lime light.

Happy reading!

Latest Posts

Related Stories