Explore C # 6.0 syntax sugar anatomy

Source: Internet
Author: User

Original address: Http://www.cnblogs.com/mushroom/archive/2015/07/22/4666113.html#six

2015-07-22 08:29 by Mr. Mushroom, 8943 read, 56 reviews, Favorites, compilation

Read the catalogue:

    1. Automatic Property Default Initialization
    2. Automatic read-only property default initialization
    3. Functions with the body of an expression
    4. An expression is a property of the principal (assigned value)
    5. Static class Import
    6. Null condition operator
    7. String formatting
    8. Index initialization
    9. Exception filter When
    10. Await in catch and finally code block
    11. nameof-expression
    12. Extension methods
    13. Summarize
Automatic Property Default Initialization

How to use:

public string Name {get; set;} = ' Hello World ';

To facilitate understanding using the 2.0 syntax display, the compiler generates the following code:

public class Customer {[compilergenerated] private string kbackingfield = ' Hello World '; public customer () {This.kbackin Gfield = "Hello World"; }public string name{    [compilergenerated]    get    {        return this.<name>k__backingfield;    }    [Compilergenerated]    Set    {        This.<name>k__backingfield = value;}}    }

From the generated code, you can see that the compiler initializes the property information when it is in the instance constructor.

Automatic read-only property default initialization

How to use:

public string Name1 {get;} = ' Hello World ';

The compiler generates the following code:

[compilergenerated] Private readonly string Kbackingfield; Public Customer () {This.kbackingfield = ' Hello World ';} public string Name1 {[compilergenerated] get {return this.k__b Ackingfield; } }

Because initializing the default value is assigned in the constructor, it doesn't matter if the property is read-only.

Functions with the body of an expression

How to use:

Body Get (int x, int y) = = new Body (1 + x, 2 + y);

The compiler generates the following:

Private Program.body Get (int x, int y) {    return new Program.body (1 + x, 2 + y);}

Simplifies the writing of single-line methods, eliminating the effort to write curly braces.

Support for writing without a return value is also supported:

void OutPut (int x, int y) = = Console.WriteLine ("Hello World");

also supports the writing of asynchronous functions:

async void OutPut (int x, int y) = await new Task (() = Console.WriteLine ("Hello wolrd"));
An expression is a property of the principal (assigned value)

How to use:

public string Name2 = "Hello World";

The compiler generates the following code:

public string Name2 {get {return ' Mushroomsir ';}}

The compiler generated only a read-only property.

Static class Import

This feature can import all static members of a type at once, leaving static members without type restrictions in subsequent code, just as with static methods below this type.


{static void Main (string[] args) {WriteLine ("Hello wolrd");}}

The compiler generates the following code:

private static void Main (string[] args) {Console.WriteLine ("Hello wolrd");}

The repetition of the type name is omitted.

Null condition operator

How to use:

Customer customer = new Customer ();
String Name3 = Customer?. Name;

Equivalent to:

Customer customer = new Customer (); if (customer1! = null) {    string name = Customer1. Name;}

Can and?? Combine to use:

if (customer?. Face2 ()?? False

can also be used together with 2:

Int? Length = customer?. Name?. Length;

You can also call the method:

Customer?. Face ();

The purpose of this syntax sugar is to check for null before the object is used. if the object is empty, the variable is assigned a null value, so an int, or int, that can be empty is required in the example.

If the object is not empty, the member of the calling object is evaluated and assigned to the variable.

String formatting

String.Format Some inconvenient place is: Must enter "String.Format", use {0} placeholder, must order to format, this is error-prone.

var s = String.Format ("{0} is {1} year {{s}} old", P.name, P.age);

The new syntax sugar is relatively easier to use:

var s = $ "{P.name} is {p.age} year{{s}} old";

The compiler generates the following, with no distinction before:

var s = String.Format ("{0} is {1} year{{s}} old", P.name, P.age);

Interestingly, the new format also supports direct assignment of any expression:

var s = $ "{P.name} is {p.age} year{(p.age = = 1?) "": "S")} old ";
Index initialization

List Although this can be compiled through, but will throw an exception, using the method:

var numbers = new List<string> {[7] = "Seven", [9] = "Nine", [[] = "Thirteen"};

The compiler generates the following code:

List List = new List (); LIST[7] = "seven"; LIST[9] = "Nine"; LIST[13] = "Thirteen";

Dictionary can be executed because the internal indexing mechanism is different:

var numbers = new Dictionary<int, string> {[7] = "Seven", [9] = "Nine", [[] = "Thirteen"};

Compiler generated code:

Dictionary<int, string> dictionary2 = new Dictionary<int, string> ();    DICTIONARY2[7] = "seven";    DICTIONARY2[9] = "Nine";    DICTIONARY2[13] = "Thirteen";    Dictionary<int, string> Dictionary = Dictionary2;
Exception filter When

How to use:

Try {throw new ArgumentException ("string Error"),} catch (ArgumentException e) when (Myfilter (e)) {Console.WriteLine (E. Message); }static bool Myfilter (ArgumentException e) {return false;}

When the syntax function is: Before entering the catch, validating when the Myfilter method returns the bool, if the return true continues to run, false does not go catch directly throws an exception.

Using this filter is a good way to tell if an error is to continue or re-throw. According to the previous practice, in the catch block if you want to throw again, you need to re-throw out, the source of the error is caught after the throw, rather than the original, with when the syntax can be directly located to the source of the error.

Await in catch and finally code block

Await asynchronous processing is presented in c#5.0, but cannot be used within catch and finally blocks, this time supported on the c#6.0 update.

How to use:

    Async void Solve ()    {        Try        {            await httpmethodasync ();        }        catch (ArgumentException e)        {            await httpmethodasync ();        }        Finally        {            await httpmethodasync ();        }    }

The compiler generates the catch and finally await into the MoveNext () inside the state machine. The original inside only Taskawaiter, now more than 2. State machine inside the code and the same, just more complex, the interest of children's shoes can first look at async, await analysis and then go to the bottom.

nameof-expression

How to use:

String name = ""; Console.WriteLine (nameof (name));

Console output "name".

Sometimes you will need the string name of some members of the program, such as throwing ArgumentNullException exception, want to know the ArgumentNullException type string name, this time can use nameof to get the character

String "ArgumentNullException". Now the practice is to manually copy, but the refactoring renaming when it is easy to forget to change the string, the use of nameof can be avoided.

When used as follows, the compiler will only take the last zipcode.

Nameof (person. Address.zipcode)

The compiler generates the following code:

Console.WriteLine ("Name");
Extension methods
    Using static System.Linq.Enumerable; Introduces the type, not the namespace    class program    {        static void Main ()        {            var range = Range (5, +);                Ok: Not extension method            var odd = where (range, i = i% 2 = = 1);//Error, not in global scope            var even = range. Where (i = = i% 2 = = 0); Ok        }    }

First, enumerable is a static class, which is a variety of extension methods, such as range. Static is the function of the type to be a member of a single import, rang although static method, but not import, such as where.

Because the extension method is a static method, but the syntax specifies that it is used as an instance method (dot), it cannot be used in the global scope as a static method, so var odd = Where (range, i = i = 2 = = 1) is wrong.

But static can import the extension method of the type as the function of the extension method itself, so var even = range. Where (i + = i% 2 = = 0) is OK.

Here may be a little bit around, LZ try to write clearly, static new usage has 2 functions:

    1. The static members are imported, but the extension methods are special and excluded. At this point, Static is a new feature of C # 6.0.
    2. is equivalent to importing the namespace of the extension method, so you can call the extension method on the collection. This is the previous function, rather than the extension method into a purely static method import use.
Summarize

See the garden has introduced articles, for a moment to interest, after work to install a community version of the research and sharing under. Although Microsoft has been a new thing, but all from bottom to top iteration, so learning is very fast.

Reference Https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#expression-bodied-function-members

Explore the series Navigation of C #

Explore C # 6.0 syntax sugar anatomy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.