C# 6.0 có gì mới?

posted by tungnt 01/12/2015 0 comments
C# 6.0 có gì mới

1. The null-conditional (“Elvis”) operator avoids having to explicitly check for null before calling a method or accessing a type member. In the following example, result evaluates to null instead of throwing a NullReferenceException:

System.Text.StringBuilder sb = null;
string result = sb?.ToString(); // result is null

2. Expression-bodied functions allow methods, properties, operators, and indexers that comprise a single expression to be written more tersely, in the style of a lambda expression:

public int TimesTwo (int x) => x * 2;
public string SomeProperty => "Property value";

3. Property initializers let you assign an initial value to an automatic property:

public DateTime Created { get; set; } = DateTime.Now;

Initialized properties can also be read-only:

public DateTime Created { get; } = DateTime.Now;

Read-only properties can also be set in the constructor, making it easier to create immutable (read-only) types.

4. String interpolation offers a succinct alternative to string.Format:

string s = $"It is {DateTime.Now.DayOfWeek} today";

5. Exception filters let you apply a condition to a catch block:

    new WebClient().DownloadString("http://asef");
catch (WebException ex) when (ex.Status == WebExceptionStatus.Timeout)

6. The using static directive lets you import all the static members of a type, so that you can use those members unqualified:

using static System.Console;
WriteLine ("Hello, world"); // WriteLine instead of Console.WriteLine

7. The nameof operator returns the name of a variable, type or other symbol as a string. This avoids breaking code when you rename a symbol in Visual Studio:

int capacity = 123;
string x = nameof (capacity); // x is "capacity"
string y = nameof (Uri.Host); // y is "Host"

8. Allowed to await inside catch and finally blocks.

Bình luận
1570 Total Views 2 Views Today

You may also like