Use an example to learn about the new features of C #6.0,

Source: Internet
Author: User

Use an example to learn about the new features of C #6.0,

Microsoft updated the C # language to 2015 in Visual Studio 6.0, and added many excellent features so that the C # language can continue to rank among the best languages. The following example shows the new features of C #6.0. The following program has passed the test in the VS2015 preview version, and the new features may be added to the official version.

Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. console; namespace CSharp6Research {// score public class Fraction {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 I Ndex] => index = 0? A: B; public int this [string index] => index = ""? A: B; public override string ToString () => "\ {A }\{ SeparatorSpaces }\{ Separator }\{ SeparatorSpaces }\{ B}"; public void Print () => WriteLine (ToString (); public Fraction () {} public Fraction (int a, int B) {A = a; B = B;} public Fraction (int, int B, string separatorSpaces): this (a, B) {SeparatorSpaces = separatorSpaces; if (string. isNullOrEmpty (separatorSpaces) {throw new ArgumentNullException (Nameof (separatorSpaces) ;}} public static readonly Dictionary <string, Fraction> CommonFractions = new Dictionary <string, Fraction> {["zero"] = new Fraction (), ["one"] = new Fraction (1, 1), ["half"] = new Fraction (1, 2), ["quarter"] = new Fraction (1, 4), ["infinity"] = new Fraction (1, 0), };} public struct FractionStruct {public int A {get;} public int B {get ;} public FractionStruct (int, Int B) {A = a; B = B;} public FractionStruct (): this (0, 1) {} public override string ToString () => "\ {A}/\ {B}";} class Program {static void Main (string [] args) {foreach (var f in Fraction. commonFractions) {WriteLine ("\ {f. key}: \ {f. value. value} ") ;}var fraction = new Fraction (1, 3," "); fraction. print (); try {fraction = new Fraction (1, 2, null);} catch (ArgumentNullException e) if (e. ParamName = "separatorSpaces") {WriteLine ("separatorSpaces can not be null");} Fraction v; Fraction. commonFractions. 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 FractionStruct (). ToString (); WriteLine (default (FractionStruct). ToString ());}}}

The running result is as follows,

zero : 0one : 1half : 0.5quarter : 0.25infinity : ∞1 / 3separatorSpaces can not be nullTrueTrueTrue0/10/0

1. Auto-property initializers automatic attribute initializer

Public int B {get; set;} = 1;

You can assign values to the automatic attribute directly without writing it in the constructor.

2. Getter-only auto-properties read-only auto attributes

Public string SeparatorSpaces {get;} = string. Empty;

Read-Only automatic attributes can be directly initialized or initialized in the constructor.

3. Expression-bodied members Expression body member

Public double Value => (double) A/B;

Public int this [int index] => index = 0? A: B;

Public void Print () => WriteLine (ToString ());

Read-Only attributes, read-only indexers and methods can both use Lambda expressions as the Body.

4. String interpolation String embedded value

"\ {A }\{ SeparatorSpaces }\{ Separator }\{ SeparatorSpaces }\{ B }";

The expressions in the braces after the backslash calculate the value at runtime and embed it into the string. It is very similar to Swift. In Swift, the backslash is used and parentheses are added. in C #, The backslash is used to increase the parentheses.

5. nameof operator

Throw new ArgumentNullException (nameof (separatorSpaces ));

Nameof returns a variable, parameter, or member name.

This is very useful. When writing the notification of attribute changes in the ViewModel layer of WPF, you need to write a string or use the help methods in the MvvmLight library to directly pass in the attribute, however, parsing at runtime may cause a slight performance loss. Now we can use the nameof operator to ensure the security and readability of refactoring and performance.

6. Dictionary initializer

New Dictionary <string, Fraction>

{

["Zero"] = new Fraction (),

["One"] = new Fraction (1, 1 ),

["Half"] = new Fraction (1, 2 ),

["Quarter"] = new Fraction (1, 4 ),

["Infinity"] = new Fraction (1, 0 ),

};

Now, you can initialize the dictionary in a more readable way. The Key enclosed by square brackets is equal to the Value.

7. Parameterless struct ctors struct constructors without Parameters

Public FractionStruct (int a, int B) {A = a; B = B ;}

Public FractionStruct (): this (0, 1 ){}

Struct can provide custom non-parameter constructor.

New FractionStruct ()

Default (FractionStruct)

New is to call a non-parameter constructor.

Default does not call a non-parameter constructor.

8. Exception filters Exception filter

Catch (ArgumentNullException e) if (e. ParamName = "separatorSpaces ")

{

WriteLine ("separatorSpaces can not be null ");

}

Set the conditions for entering the catch Block.

9. Null propagation

V ?. A

V? ["B"]

V ?. ToString ()

If the object is null, no attribute is called, The indexer, method, and so on. The expression returns null, which is similar to the usage in Swift.

10. Using static members using static Import

Using System. Console;

WriteLine ("separatorSpaces can not be null ");

You can specify a static class in using, and then you can directly use the static method of this class in subsequent code, similar to the usage in Java.

11. Await in catch/finally catch and await in finally Blocks

Example,
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.
}

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.