Best 5 C# 6.0 Language Features

来源:互联网 发布:3d缩水软件 编辑:程序博客网 时间:2024/06/07 11:01

Best 5 C# 6.0 Language Features

# 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;
}

# ?—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;
}

# 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"};
}

# 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);
   }
}

# 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);
   }
}

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
 
http://developerbase.blogspot.com/2015/04/best-5-csharp-6-language-features.html
0 0
原创粉丝点击