C #6 syntactic sugar,

Source: Internet
Author: User

C #6 syntactic sugar,
Static Using

The static using Declaration allows you to directly call static methods without specifying the Class Name:

C #5
static void StaticUsingDemoInCSharp5(string output){    Console.WriteLine(output); // Call the static method WriteLine with class name Console}

C #6

using static System.Console;namespace NewFeatureTest{    class Program    {        static void Main(string[] args)        {            StaticUsingDemoInCSharp6("Hello, C# 6");        }        static void StaticUsingDemoInCSharp6(string output)        {            WriteLine(output);        }    }}
Expression-Bodied Methods

Expression-bodied methods is used. A function with only one statement can be written in lambda.

C #5

private static bool IsIntegerEqual(int a, int b){    return a == b;}

C #6

private static bool IsIntegerEqualWithExpressionBodied(int a, int b) => a == b;
Expression-Bodied Properties

Similar to expression-bodied methods,Only get accessors are supported.In addition, only one statement attribute (Properties) can be written in lambda.

C #5
private string firstName;public string FirstName{    get    {        return firstName;    }}
C #6
private string lastName;public string LastName => lastName;
Auto-Implemented Property Initializers

Auto-implemented Property can be initialized in a Property initiator.

C #5
public string Sex { get; set; }public Person(){    Sex = "Male";}
C #6
public int Age { get; set; } = 42; // The age will be initialized to 42 when object constructed
Read-Only Auto Properties

In the previous C # version, the read-only attribute requires the complete attribute syntax. C #6 provides an automatically implemented version:

C #5
private readonly string homeTown;public string HomeTown { get { return homeTown; } }
C #6
public string BirthDay { get; }public Person(string _firstName, string _lastName){        BirthDay = DateTime.Today.ToString();}
Nameof Operator

With the latest nameof operator, the names of fields (fields), Properties, methods, and types can all be obtained. With it, mom doesn't have to worry about missing it when changing the name.

C #5
public bool IsAdult(int age)        {            if (age < 0)            {                throw new ArgumentException("age");            }            return age >= 18;        }
C #6
public bool IsAdultWithNameOfOperator(int age)        {            if (age < 0)            {                throw new ArgumentException(nameof(age));            }            return age >= 18;        }
Null Propagation Operator

The null propagation operator can greatly simplify empty object checks.

C #5
public Person(int? _age){    Age = _age == null ? -1 : _age.Value;}
C #6
public Person(DateTime? _birthDay){    birthDay = _birthDay?.ToString();}
String Interpolation

In c #6, you do not need to call the string. Format Method for string interpolation. Compared with the previous use of digit placeholders such as {0} In string, C #6 supports expression placeholders such as {age }.

C #5
public override string ToString(){    return string.Format("{0} {1}”, firstName, lastName);}
C #6
public override string ToString() => $"{firstName} {lastName}";

Here, we use the new string interpolation and expression-bodied method to make the entire code much simpler than before (the Code farmer who calculates money by the number of lines of code is miserable ).

Dictionary Initializers

In C #6, we can use the Dictionary initialization tool to initialize Dictionary objects like the set initialization tool.

C #5
var dictInCSharp5 = new Dictionary<int, string>(){    {2, "Two"},    {1, "One"}};
C #6
var dictInCSharp6 = new Dictionary<int, string>(){    [2] = "Two",    [1] = "One"};

I personally think this is useless, but it is easy to be confused with the subscript of Collection.

Exceptions Filters

The exception filter allows us to use conditions to filter exceptions before catch exceptions.

C #5
try{    StaticUsingDemoInCSharp6(p.LastName);}catch (Exception e){    if (e.Message.Contains("Aha"))    {        throw;    }}
C #6
try{    StaticUsingDemoInCSharp6(p.LastName);}catch(Exception e) when (e.Message.Contains("Aha")){    throw;}
Await in Catch

C #6 allows us to use the await keyword in the catch Block. In c #5, we can only work around und.

C #5

private static async Task AwaitInCatchDemoInCSharp5(){    bool hasError = false;    string errorMessage = string.Empty;    try    {        throw new FieldAccessException("No Permission.");    }    catch(FieldAccessException e)    {        hasError = true;        errorMessage = e.Message;    }    if(hasError)    {        await MessageDialog().ShowAsync(errorMessage);    }}

C #6

private static async Task AwaitInCatchDemoInCSharp5(){    try    {        throw new FieldAccessException("No Permission.");    }    catch(FieldAccessException e)    {        await MessageDialog().ShowAsync(e.Message);    }}

Reference: Professional C #6 and. NET Core 1.0

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.