понедельник, 1 февраля 2016 г.

Новые возможности C# 6.0

Перевод статьи New Features of C# 6.0

В этой статье мы познакомимся с новыми ключевыми фишками и усовершенствованиями, появившимися в C# 6.0.

Автоматически реализуемые свойства:

Эта штука позволяет нам задать значения свойств на этапе их объявления.
Previously, we use constructor to initialize the auto properties to non-default value but with this new feature in C# 6.0, it doesn’t require to initialize these properties with a constructor aкак показано ниже:

class Customer
{
    public string Firstname{get; set;} = "Csharpstar";
    public string Lastname{get; set;} = "Admin";
    public int Age{get;} = 20;
    public DateTime BirthDate { get; set; }
}
We can use this property with getter/setter and getter only.Using getter only help achieve immutability.

Фильтры исключений:

Microsoft introduced this CLR feature in C# with version 6.0 but it was already available in Visual Basic and F#. To use Exception Filters in C#, we have to declare the filter condition in the same line as that of the catch block and the catch block will execute only if the condition is successfully met as shown below:

try
{
throw new CustomException("Test Exception")
}
catch(CustomException ex) if (ex.Message=="Not Test")
{
//Control will not come here because exception name is not test
}
catch(CustomException ex) if (ex.Message=="Test Exception")
{
//Control will come here because exception name is Test Exception
}
 
Remember that Exception Filter is a debugging feature rather than a coding feature. We will discuss more on this in next post

Await в блоках catch и finally block:

We frequently log exceptions to a log file or a database. Such operations are resource extensive and lengthy as we would need more time to perform I/O. In such circumstances, it would be great if we can make asynchronous calls inside our exception blocks. We may additionally need to perform some cleanup operations in finally block which may also be resource extensive.

try
{
// code that might throw exception
}
catch(Exception ex)
{
await LogExceptionAsync(ex);
}

Getter-only Auto Properties

When you use auto implemented properties in C# 5 and lower, you must provide a get and set. If you want the property value to be immutable, you can use the private accessor on the setter. With C# 6, you can now omit the set accessor to achieve true readonly auto implemented properties:

 
public DateTime BirthDate { get; }

Интерполяция строк

String.Format was used till today to generate the FullName value in the Customer class.A new feature named string interpolation provides a large improvement in this area. Rather than filling placeholders with indexes provide an array of values to be slotted in at runtime, you provide the source of the parameter value instead, and the string.Format call is replaced by a single $ sign. This is how the FullName property declaration looks when using string interpolation in the expression body instead:

 
public string FullName => $"{FirstName} {LastName}";
Apart from this saving a number of key strokes, it should also minimise (if not remove) the possibility of FormatExceptions being generated from inadvertently supplying too few values to the argument list.

Инициализация словарей:

В C# 6.0 появился более прозрачный путь для инициализации словарей (см. ниже):

 
var BookDictionary = new Dictionary<int,string>
{
[1] = "ASP.net",
[2] = "C#.net",
[3] = "ASP.net Razor",
[4] = "ASP.net MVC5"
}
А раньше было так:
Dictionary<int,string> BookDictionary = new Dictionary<int,string>()
{
{1, "ASP.net"},
{2, "C#.net"}
{3, = "ASP.net Razor"},
{4, = "ASP.net MVC5"}}
};

Null – условный оператор:

Null-условный оператор “?” использует одинарный знак вопроса. It can be used to reduce the no. of lines in code file and provide an easy access to check for Null and return the result. The null conditional operator tests for null before accessing a member of an instance. Пример:

using System;

class Program
{ static void Test(string name)
    {
 // Use null-conditional operator.
 // ... If name is not null, check its Length property.
 if (name?.Length >= 3)
 {
     Console.WriteLine(true);
 }
    }
    static void Main()
    {
 Console.WriteLine(1);
 Test(null);
 Console.WriteLine(2);
 Test("Csharpstar"); // True.
 Test("x");
 Test("ExamIron"); // True.
    }
}
Выводится:1
2
True
True

0 коммент.:

Отправить комментарий