C# 6.0 Grammatical Sugar Analysis

  1. Automatic property initialization by default:
    public string Name { get; set; } = "hello world";

     

  2. Default initialization of automatic read-only properties

    public string Name1 { get; } = "hello world";

    Since initializing default values is actually assigned in the constructor, it has nothing to do with property read-only.

  3. A function whose expression is the main body

    //Usage method:
    
    Body Get(int x, int y) => new Body(1 + x, 2 + y);
    //The compiler is generated as follows:
    
    private Program.Body Get(int x, int y)
    {
        return new Program.Body(1 + x, 2 + y);
    }
    //It simplifies the compilation of single-line method and saves the effort of writing brackets.
    
    //It also supports the writing of no return value: 
    
    void OutPut(int x, int y) => Console.WriteLine("hello world");
    //It also supports the writing of asynchronous functions:
    
    async void OutPut(int x, int y) => await new Task(() => Console.WriteLine("hello wolrd"));

     

  4. Null conditional operator

    Customer customer = new Customer();
     string name3 = customer?.Name;
    //The same as:
    
    Customer customer = new Customer();
    if (customer1 != null)
    {
        string name = customer1.Name;
    }
    //It can be combined with???
    
    if (customer?.Face2()??false)
    //Two more can be used together:
    
    int? Length = customer?.Name?.Length;
    //Method calls can also be made:
    
    customer?.Face();

     

  5. String formatting
    //I see
    var s = String.Format("{0} is {1} year {{s}} old", p.Name, p.Age);
    
    //The new grammatical sugar is relatively easy to use:
    var s = $"{p.Name} is {p.Age} year{{s}} old";
    
    //Interestingly, the new formatting also supports direct assignment of any expression:
    var s = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";
     
  6. Index initialization
    var numbers = new List<string> { [7] = "seven", [9] = "nine", [13] = "thirteen" };

     

  7. Exception filter when
    try 
    { 
       throw new ArgumentException("string error");
     }
     catch (ArgumentException e) when (myfilter(e))
     { 
        Console.WriteLine(e.Message);
     }
    
    static bool myfilter(ArgumentException e)
     { 
        return false;
     }
     

    The function of When grammar is to verify the bool returned by the myfilter method in when brackets before entering catch, and if true continues to run, false throws an exception without catch.

    Using this filter, you can better judge whether an error is to continue processing or to re-throw. According to the previous practice, if you want to throw it again in the catch block, you need to throw it again. At this time, the error source is thrown after catching, not the original. With when grammar, you can directly locate the error source.  

  8. nameof expression
    string name = "";
    Console.WriteLine(nameof(name));
     
  9. Extension method
    using static System.Linq.Enumerable; //Introduce types, not namespaces
        class Program
        {
            static void Main()
            {
                var range = Range(5, 17);                // Ok: Not an extension method
                var odd = Where(range, i => i % 2 == 1); // Error, not in global scope
                var even = range.Where(i => i % 2 == 0); // Ok
            }
        }
     

    First, Enumerable is a static class with various extension methods, such as range. Static's function is to import static members of a type at one time. rang is a static method, but it can't be imported, such as where.

    Because the extended method is a static method, but the grammar stipulates that it is used as an instance method (dotting), so it cannot be used as a static method in the global scope, so var odd = Where (range, I = > i%, 2 = 1) is wrong.

    But static can import the type extension method as the function of the role of the extension method itself, so var even = range. Where (i = > i% > 2 = 0) is ok.

    There may be a slight twist here, lz try to write clearly, the new use of static has two functions:

One is to import static members, but the extension method is special and excluded. Static is a new function of c# 6.0.

Second, it is equivalent to importing the namespace of the extended method, so the extended method can be called on the set by dots. This is a function that existed before, rather than turning the extended method into a simple static method to be imported into use.

Posted by Debar on Wed, 20 Mar 2019 16:27:26 -0700