C # 10 You really should learn (and use!) ) Features of

Source: Internet
Author: User
If you start exploring C # or decide to expand your knowledge, then you should learn these useful language features, which will help simplify the code, avoid mistakes, and save a lot of time.

  

1) async/await

Use Async/await-pattern to allow the UI to be unblocked when a blocking operation is performed or when the thread is blocked. Async/await-pattern works by letting the code continue to execute, even if something is blocking execution (such as a Web request).


2) object/array/set initializer

You can easily create instances of classes, arrays, and collections by using objects, arrays, and collection initializers:


Some demo classes publicclassemployee{publicstringname {get; set;} publicdatetime startdate {get; set;}}//use initializer to create employee Emplo Yee emp = newemployee {name= "John Smith", Startdate=datetime.now ()};


The above example is really useful in unit tests, but should be avoided in other contexts, because instances of classes should be created using constructors.


3) Lambdas, predicates, delegates and closures

In many cases, such as when using LINQ, these features are actually necessary to ensure that you learn when and how to use them.


4)?? (empty merge operator)

?? – The operator returns to the left, as long as it is not null, and in that case returns to the right:


Possible for nullvarsomevalue = service. GetValue (); Vardefaultvalue = 23//If somevalue is null, the result will be 23varresult = somevalue?? DefaultValue;


?? – Operators can link:

Stringanybody = Parm1?? Localdefault?? Globaldefault;


And it can be used to convert a nullable type to non-nullable:

vartotalpurchased = purchasequantities.sum (kvp = kvp. Value?? 0);


5) $ "{x}" (String interpolation)--c#6


This is a new feature of c#6 that allows you to assemble strings in an efficient and elegant way:


Old Method varsomestring = String.Format ("Some data: {0}, Some more data: {1}", somevariable, someothervariable); New Method varsomestring = $ "Some data: {somevariable}, Some more data: {someothervariable}";


You can put a C # expression between curly braces, which makes this string interpolation very powerful.


6)?. (Null conditional operator)--c#6

The null conditional operator works as follows:


Null ifcustomer orcustomer.profile orcustomer.profile.age Isnullvar currentage = customer?. Profile?. Age


No More nullreferenceexceptions!


7) nameof Expression--c#6

The new nameof-expression may not seem important, but it really has its value. When using the automatic refactoring factor tool (such as ReSharper), you sometimes need to refer to method parameters by name:


Publicvoid Printusername (usercurrentuser) {//the refactoring tool might miss the textual reference to current user below Ifwe ' re renaming it if (CurrentUser = = null) _logger. Error ("Argument CurrentUser is not provided"); //...}


You should use it like this ...


Publicvoidprintusername (User currentUser) {//the refactoring tool would not miss this...if (currentUser = = null) _logger. Error ($ "Argument {nameof (CurrentUser)}is not provided"); //...} 8)--c#6 of the property initializer


The property initializer allows you to declare the initial value of a property:

publicclassuser{publicguidid{get;} = Guid. NewGuid (); // ...}


One advantage of using a property initializer is that you cannot declare a collection: Well, this makes the property immutable. The property initializer works with the C#6 primary constructor syntax.


9) As and is operators


The IS operator is used to control whether an instance is of a specific type, for example, if you want to see if it is possible to convert:


if (personisadult) {//do stuff}


Use the as operator to attempt to convert an instance to a class. If it cannot be converted, it will return null:


SomeType y = x assometype; if (Y! = null) {//do stuff}) yield keyword


The yield keyword allows you to provide an IEnumerable interface with an entry. The following example returns the power of each 2, the power exponent from 2 to 8 (for example, 2,4,8,16,32,64,128,256):


Publicstaticienumerable Power (intnumber, intexponent) {intresult = 1; for (inti = 0; i < exponent; i++) {result = ResU LT * number; Yieldreturnresult; }}


The

yield return can be very powerful if it is used in the correct way. It allows you to lazily generate a series of objects, that is, the system does not have to enumerate the entire collection-it will be done as needed.

Related Article

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.