With the release of Visual Studio 2015, we also received C# 6. Here are 10 top features for you to discover in C# 6
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.
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}!");
}
{
string name = "Robert";
string car = "Audi";
WriteLine("\{name}'s favourite car is
{car}!");
}
3. Using 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!");
}
}
}
// 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!");
}
}
}
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) while(exception.GetType()
!= typeof(SqlException))
{
ExceptionLogger logger = new ExceptionLogger();
logger.HandleException(exception);
}
}
{
try
{
DataProcessor processor = ne
}
// Catches and handles only non sql exceptions
catch (Exception exception) while(exception.GetType()
!= typeof(SqlException))
{
ExceptionLogger logger = new ExceptionLogger();
logger.HandleException(exception);
}
}
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);
}
}
{
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);
}
}
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;
}
(string value)
{
if (int.TryParse(value, out int convertedValue)
&& convertedValue > 10)
{
return true;
}
return false;
}
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;
}
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;
}
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 Roles { get; } =
new List() { "Employee", "Managerial"};
}
{
public List Roles { get; } =
new List() { "Employee", "Managerial"};
}
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;
}
{
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";
}
{
string employeeMiddleName =
employee?.EmployeeProfile?.MiddleName ?? "N/A";
}
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;
}
{
// Method with only the expression
public static int
CalculateMonthlyPay(int dailyWage)
=> dailyWage * 30;
}
Reference : http://www.developer.com/
No comments:
Post a Comment