C #6.0 new features,

Source: Internet
Author: User

C #6.0 new features,

Because the project has been upgraded. netFramework 4.6.1, the development tool switched to vs2015, and took the opportunity to try C #6. 0. the results of some online search tutorials are not too complete, and some code has been modified with the release of the official vs version. those tutorials were not updated.
So record what you learned.

1. Auto-property initializers)
    public class Account    {        public string Name { get; set; } = "summit";        public int Age { get; set; } = 22;        public IList<int> AgeList        {            get;            set;        } = new List<int> { 10,20,30,40,50 };    }

The read-only attribute can also be directly initialized (C #5.0 is not supported), or directly initialized in the constructor.

public class Customer{    public string Name { get; }    public Customer(string first, string last)    {        Name = first + " " + last;    }}
2. String interpolation)


In earlier versions. the number of parameters in the Format must be encoded with placeholders in order. Otherwise, an error is returned. too many parameters. in the new version, $ is used before the string to identify the following characters. {object} can be used as a placeholder. let's look at an example.

Console. writeLine ($ "Age: {account. age} Birthday: {account. birthDay. toString ("yyyy-MM-dd")} "); Console. writeLine ($ "Age: {account. age} "); Console. writeLine ($ "{(account. age <= 22? "Small meat": "old meat ")}");

To output the {or} symbol, write two characters, for example, $ "{{".
Pay attention to this $ symbol. N many tutorials on the Internet do not have this stuff. It is a direct "\ {account. Age \}". This method has been abandoned in the new version.

3. Import a Static class (Using Static)


Before using the static Math class, you must first import it to the System namespace before using it. Now you can directly import this static class and then directly use its function in the code.

Using static System. math; // note that this is not a namespace. writeLine ($ "previous usage: {Math. pow (4, 2)} "); Console. writeLine ($ "direct usage after import: {Pow )}");

Note that this is using static...
If a namespace contains n methods, it is quite convenient to directly introduce a single static class without referencing all the methods.

4. Null operator (Null-conditional operators)


Countless such judgment codes have been written before

If (***! = Null) {// action not null} return null;

This method can be simplified.

var age = account.AgeList?[0].ToString();Console.WriteLine("{0}", (person.list?.Count ?? 0));

If account. AgeList is null, the entire expression returns NULL; otherwise, the value of the following expression is returned.

5. Index Initializers)


In this way, the dictionary or other objects can be initialized by assigning values to the index.

IDictionary<int, string> dict = new Dictionary<int, string>() {       [1]="first",       [2]="second"};foreach(var dic in dict){    Console.WriteLine($"key: {dic.Key} value:{dic.Value}");}output:key: 1 value:firstkey: 2 value:second
6. Exception filters)
Private static bool Log (Exception e) {Console. writeLine ("log"); return true;} static void TestExceptionFilter () {try {Int32.Parse ("s");} catch (Exception e) when (Log (e )) {Console. writeLine ("catch"); return;} when the value returned in when () is not true, an exception is continuously thrown and the methods in the catch are not executed.
7. nameof expression (nameof expressions)
When checking method parameters, it is often written as follows: private static void Add (Account account) {if (account = null) throw new ArgumentNullException ("account ");} if the parameter name is modified one day, the following strings are easily missed and you forgot to modify them. after the nameof expression is used, the compiler will check whether there is any modification and then automatically navigate and refactor (-_-! I do not know if the translation is correct.) private static void Add (Account account) {if (account = null) throw new ArgumentNullException (nameof (account ));}
8. Use await (Await in catch and finally blocks) in the cath and finally statement blocks)
C #5.0 does not support writing. Resource res = null; try {res = await Resource. OpenAsync (...); // You cocould do this ....} Catch (ResourceException e) {await Resource. LogAsync (res, e); // Now you can do this ...} Finally {if (res! = Null) await res. CloseAsync ();//... And this .}
9. Use the Lambda Expression (Expression bodies on property-like function members) in the attribute)
Public string Name => string. Format ("Name: {0}", "summit"); public void Print () => Console. WriteLine (Name );
10. Use Lambda expressions on method members
static int LambdaFunc(int x, int y) => x*y;public void Print() => Console.WriteLine(First + " " + Last);

 

There are so many new language features in C #6.0 so far. There are no new features, more improvements to syntactic sugar, and more comfortable and fast development.
The link to c #6.0 on github is attached.

  

 

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.