c#6.0 new Features

Source: Internet
Author: User

I. Development history of C #

It is helpful to understand C # 's understanding of the evolution of C # over the years, by collating and listing the time and the new features of each important update in C #.

Ii. New characteristics of c#6.0

1, string interpolation (string interpolation)

String stitching Optimization

Before:

var Name = "Joye.net"; var Results = "Hello" + name;//direct concatenation var results1 = string. Format ("Hello {0}", Name);//format stitching

After:

var results2 = $ "Hello {Name}"; $ splicing var results= $ "Hello {name}{new program (). Getcnblogssite ()} ";//{} can be inserted directly into the code

2, NULL check operator "?. "(monadic null checking)

Null optimizations

Before:

        public static string Getcnblogssite ()        {            return ' HTTP://WWW.CNBLOGS.COM/YINRQ ';        
Program Pro = Null;if (pro!=null)      Console.WriteLine (Getcnblogssite ());

After:

program pro = NULL; Console.WriteLine (pro?. Getcnblogssite ());

3. Automatic property initializer (initializers for auto-properties)

You can assign values to automatic attributes directly, and do not need to be written in the constructor.

Before:

    public class ClassA    {        private string name{get;set;};        Public ClassA ()        {            Name = "joye.net";        }     }

After:

    public class ClassA    {public        string Name {get; set;} = "Joye.net";       }

4. Read-only automatic attributes (Getter-only auto-properties)

Read-only automatic attributes can be initialized directly or initialized in constructors.

Before

Reduce access to automatic properties public    class ClassA    {public        string Name {get; private set;}       }    c#1.0 implement public    class ClassA    {        private string Name = "Joye.net";        public string name        {            get {return Name;}        }    }

After

    public class ClassA    {public        string Name {get;} = "Joye.net";    }

5, Expression method Body (property Expressions && method Expressions)

Read-only properties, read-only indexers, and methods can all use lambda expressions as body.

The method body of a sentence can be written directly into the arrow function, but no longer need curly braces (the paging control http://www.cnblogs.com/yinrq/p/5586841.html is used to attribute Expression property Expressions)

    public class Pagerinbase {//<summary>///        Current page//</summary> public        int PageIndex { Get Set }//<summary>///page///        </summary> public        int PageSize {get; set;}
The previous wording
public int Skip{get{return (PageIndex-1) * PageSize}}
Skips a specified number of elements in a sequence public int skip = (PageIndex-1) * PageSize; <summary>//Request URL/// </summary> public String requeturl = System.Web.HttpContext.Current.Request.Url.OriginalString; <summary>/ //The constructor initializes the current page and number of pages/// </summary> public pagerinbase () { if ( PageIndex = = 0) PageIndex = 1; if (PageSize = = 0) PageSize = ten; } }

Method expression (Methods Expressions)

        Before full method public        int Skip ()        {             return (PageIndex-1) * PageSize        }        //after c#6.0 method Expression        public int Skip () = (PageIndex-1) * PageSize;

6. Using static class (static type using statements)

Using System; using static System.Math; Namespace ConsoleApplication1    {        class program        {            static void Main (string[] args)            {                Console.WriteLine (LOG10 (5) + PI);}}}    

7. Check method parameter nameof expression (nameof expressions)

This is useful when you write a property change notification for a viewmodel layer in WPF, you need to write a string, or use a Help method in a library such as Mvvmlight, you can pass in the property directly, but because it is parsed at run time, there is a slight performance penalty. The nameof operator is now used to ensure refactoring security and readability, while improving performance.

Before:

        public static void Add (person person)        {            if (person = = null)            {                throw new ArgumentNullException ("person") ;            }        }

After:

        public static void Add (person person)        {            if (person = = null)            {                throw new ArgumentNullException ( Nameof ("person"));            }        }

8, indexed object initializer (index initializers)

Initializing an object directly from an index

var dic = new Dictionary<int, string> {[0]= "joye.net", [1]= "http://yinrq.cnblogs.com/", [2]= "Index Initializers"} ;

9. Use await in catch and finally (await in catch and finally)

In c#5.0, the await keyword cannot appear in catch and finnaly blocks. and c#6.0 can

            Try            {                res = await resource.openasync (...);//You could does this            }            catch (Resourceexception e)            {                Await Resource.logasync (res, E); Now, can do this            }            finally            {                if (res! = NULL)                    await Res. Closeasync (); Finally and do the.             }

10, inline out parameters (inline declarations for out params)

Before

int X;int. TryParse ("123", out X);

After

Int. TryParse ("123", out int x);

11. struct constructor without parameters (parameterless constructors in structs)

    public struct MyStruct    {public        int A {get;}        public int B {get;}        Public mystruct (int a, int b) {a = A; b = b; } public        MyStruct (): This (0, 1) {}    }
     WriteLine (New MyStruct (). ToString ());     WriteLine (Default (MyStruct). ToString ());
Third, the Code
Using system;using system.collections.generic;using static system.console;namespace consoleapplication1{public class        MyClass {public int A {get; set;}        public int B {get; set;} = 1;        public string Separator {get;} = "/"; public string Separatorspaces {get;} = String.        Empty;        public double Value = = (double) A/b; public int This[int Index] = index = = 0?        A:B; public int this[string index] = = Index = = "A"?        A:B;        public override string ToString () = "{a}{separatorspaces}{separator}{separatorspaces}{b}";        public void Print () = WriteLine (ToString ());            Public MyClass () {} public MyClass (int a, int b) {a = A;        b = b; } public MyClass (int A, int. B, String separatorspaces): This (A, b) {separatorspaces = separator            Spaces; if (string. IsNullOrEmpty (separatorspaces)) {throw new ARgumentnullexception (nameof (separatorspaces)); }} public static readonly dictionary<string, myclass> Dic = new dictionary<string, MYCL ass> {["zero"] = new MyClass (), ["one"] = new MyClass (1, 1), [ "Half"] = new MyClass (1, 2), ["quarter"] = new MyClass (1, 4), ["infinity"] = new MyClass (1,    0),};        } public struct MyStruct {public int A {get;}        public int B {get;} Public mystruct (int a, int b) {a = A; b = b;    Public MyStruct (): This (0, 1) {} public override string ToString () = "{a}{b}";            } class Program {static void Main (string[] args) {foreach (var f in myclass.dic)            {WriteLine ("{F.key}: {f.value.value}");            } var fraction = new MyClass (1, 3, ""); Fraction.            Print ();       try {         fraction = new MyClass (1, 2, NULL);                    } catch (ArgumentNullException e) {if (E.paramname = = "Separatorspaces")            WriteLine ("separatorspaces can not is null");            } MyClass v;            MyClass.Dic.TryGetValue ("Harf", out v); V?.            Print (); var a = v?.            A            WriteLine (A = = null); var B = v?            ["B"];            WriteLine (b = = null); WriteLine (v?.            ToString () = = null); WriteLine (New MyStruct ().            ToString ()); WriteLine (Default (MyStruct).        ToString ()); }    }}

c#6.0 new Features

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.