New Language Features in C # 6

Source: Internet
Author: User

Source:https://github.com/dotnet/roslyn/wiki/new-language-features-in-c%23-6

This document describes the new language features in C # 6, the next version of C #. All of these is implemented and available in VS 2015.

Auto-property Enhancementsinitializers for Auto-properties

You can now add the initializer to an auto-property, just as can in a field:

customer{    "Jane" Doe";}  

The initializer directly initializes the backing field; It doesn ' t work through the setter of the Auto-property. The initializers is executed in order as written, just as–and along With–field initializers.

Just like field initializers, Auto-property initializers cannot reference –after all this They is executed before the O Bject is properly initialized.

Getter-only auto-properties

Auto-properties can now is declared without a setter.

customer{    "Jane" Doe";}  

The backing field of a getter-only Auto-property is implicitly declared as readonly (though this matters only for reflection purposes). It can be initialized through a initializer on the same as in the example above. Also, a Getter-only property can is assigned to in the declaring type ' s constructor body, which causes the value of be Igned directly to the underlying field:

customer{    Customer ("+ Last;}} 

This was about expressing types more concisely, but note that it also removes a important difference in the language betwe En mutable and immutable types:auto-properties were a shorthand available only if you were willing to make your class Mut Able, and so the temptation to default to is great. Now, with Getter-only Auto-properties, the playing field has been leveled between mutable and immutable.

expression-bodied function members

Lambda expressions can be declared with an expression body as well as a conventional function body consisting of a block. This feature brings the same convenience to function members of types.

Expression bodies on Method-like members

Methods as well as user-defined operators and conversions can is given an expression body by use of the "Lambda Arrow":

Public Point Move (operator + (Complex A, Complex b) = A.add (b);"+ p.last; 

The effect is exactly the same as if the methods had had a block body with a single return statement.

For void-returning Methods–and Task -returning Async methods–the Arrow Syntax still applies, but the expression Follo Wing the arrow must be a statement expression (just as was the rule for lambdas):

"+ last);
Expression bodies on Property-like function members

Properties and indexers can have getters and setters. Expression bodies can used to write getter-only properties and indexers where the body of the getter are given by the ex Pression body:

"+ Last;  this[  

Note that there is no keyword:it are implied by the use of the get expression body syntax.

Using Static

The feature allows all the accessible static members of a type to be imported, making them available without qualification In subsequent code:

Static System.Console;  static System.Math;  Static System.dayofweek; Main () {WriteLine (Sqrt (4)); WriteLine (Friday-monday); }}

This was great for if you had a set of functions related to a certain domain. System.Mathwould is a common example of that. It also lets you directly specify the individual named values of a enum type, like the members System.DayOfWeek above.

Extension methods

Extension methods is static methods, but is intended to be used as instance methods. Instead of bringing extension methods into the global scope, the using static feature makes the extension methods of the T Ype available as extension methods:

 using static System.Linq.Enumerable; //the type, not the Namespaceclass program{static void main () {var range = Range ( 5, 17); //ok:not extension var odd = Where (range, i = i% 2 = = 
                 
                  1); 
                  //Error, not in scope var even = range. Where (i = i% 2 = = 0); //OK}}      
                         

This does mean the it can now is a breaking change to turn an ordinary static method into an extension method, which was The case before. But extension methods was generally only called as static methods in the rare cases where there was an ambiguity. In those cases, it seems right to require full qualification of the method anyway.

Null-conditional operators

Sometimes code tends to drown a bit in null-checking. The null-conditional operator lets you access members and elements if the receiver is not-null, providing a null RE Sult otherwise:

Null if customers is nullcustomer first = customers? [0];  //NULL if customers is null 

The null-conditional operator is conveniently used together with the null coalescing operator ?? :

0 if customers is null

The null-conditional operator exhibits short-circuiting behavior, where an immediately following chain of member accesses, Element accesses and invocations would only be executed if the original receiver is not NULL:

Int? First = customers? [0]. Orders.count ();

This example are essentially equivalent to:

NULL)? customers[null;

Except that's only customers evaluated once. None of the member accesses, element accesses and invocations immediately following the is ? executed unless customers ha s a non-null value.

Of course null-conditional operators can themselves be chained, in case there are a need to check for null more than once I N A chain:

Int? First = customers? [0]. Orders?. Count ();

Note that an invocation (a parenthesized argument list) cannot immediately follow the ? operator–that would leads to T OO many syntactic ambiguities. Thus, the straightforward to calling a delegate only if it's there does not work. However, you can do it via the This method on the Invoke delegate:

False) {...}

We expect that a very common use of the This pattern would be is for triggering events:

PropertyChanged?. Invoke (this, args);

This is a easy and thread-safe-to-check for NULL before trigger an event. The reason it's thread-safe is so the feature evaluates the left-hand side only once, and keeps it in a temporary VARIAB Le.

String interpolation

String.FormatAnd its cousins was very versatile and useful, but their use is a little clunky and error prone. Particularly unfortunate {0} is the use of etc. placeholders in the format string, which must line up with arguments sup Plied separately:

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

String interpolation lets you put the ' expressions right ' in the their place and by has "holes" directly in the string literal:

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

Just String.Format As with, optional alignment and format specifiers can is given:

var s = $"{p.name,20} is {p.age:d3} year{{s}} old"; 

The contents of the holes can be pretty much any expression, including even other strings:

var s = $"" s")} old";   

Notice that the conditional expression was parenthesized, so and the : "s" doesn ' t get confused with a format specifier.

nameof expressions

Occasionally you need to provide a string, names some program Element:when throwing an you ArgumentNullException want to name the GU Ilty argument; When raising a PropertyChanged is want to name of the property that changed, etc.

The Using string literals for this purpose are simple, but error prone. Spell it wrong, or a refactoring may leave it stale. Nameof expressions is essentially a fancy kind of string literal where the compiler checks so you have something of the Given name, and Visual Studio knows what it refers to, so navigation and refactoring would work:

(new ArgumentNullException (nameof (x));

Can put more elaborate dotted names in a nameof expression, but that's just to tell the compiler where to look:only t He final identifier'll be used:

Prints "ZipCode"
Index initializers

Object and collection initializers is useful for declaratively initializing fields and properties of objects, or giving a Collection an initial set of elements. Initializing dictionaries and other objects with indexers are less elegant. We is adding a new syntax to object initializers allowing your to set values to keys through any indexer that the new Obje CT has:

New dictionary<string> {    ["seven", ["nine", ["Thirteen"};   
Exception Filters

VB has them. F # has them. Now C # has them too. This is what the They look like:

try {...} catch (MyException e) when (Myfilter (e)) {    ...}

If the parenthesized expression evaluates to True, the catch block is run, otherwise the exception keeps going.

Exception filters is preferable to catching and rethrowing because they leave the stack unharmed. If The exception later causes the stack to being dumped, you can see where it originally came from, rather than just the last Place it is rethrown.

It is also a common and accepted form of the "abuse" to use exception filters for side effects; e.g. logging. They can inspect an exception ' flying by ' without intercepting its course. In those cases, the filter would often is a call to a false-returning helper function which executes the side effects:

False }...  catch (Exception e) when (Log (e)) {}
Await in catch and finally blocks

In C # 5 We don't allow await the keyword in catch and finally blocks, because we ' d somehow convinced ourselves N ' t possible to implement. Now we ' ve figured it out, so apparently it wasn ' t impossible after all.

This has actually been a significant limitation, and people had had to employ unsightly workarounds to compensate. That is no longer necessary:

Null try{    await Resource.openasync (...);       //You could does this.    catch (Resourceexception e) {    //Now, can do ...} //... and this.}     

The implementation is quite complicated, and you don ' t has to worry about that. That's the whole point's having an async in the language.

Extension ADD methods in collection initializers

When we first implemented collection initializers in C #, the Add methods that get called couldn ' t is extension methods. VB got it right from the start, but it seems we forgot about it in C #. This have been fixed:the code generated from a collection initializer would now happily call an extension method called . It's not much for a feature, but it's occasionally useful, and it turned out implementing it's in the new compiler amounted t o Removing a check that prevented it.

Improved overload resolution

There is a number of small improvements to overload resolution, which would likely result in more things just working the The expect them to. The improvements all relate to "betterness", haven the compiler decides which of the overloads are better for a given AR Gument.

One place where do might notice this (or rather stop noticing a problem!) are when choosing between overloads taking Nulla BLE value types. Another is while passing method groups (as opposed to lambdas) to overloads expecting delegates. The details aren ' t worth expanding on here–just wanted to let you know!

New Language Features in C # 6

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.