Application and summary of 10 new features in C 6.0

  • 2021-09-11 21:03:56
  • OfStack

On July 21, 2015, Microsoft released Visual Studio 2015, NET 2015, NET Framework 4.6, ASP. NET 4.6, Azure SDK 2.7 for. NET, C # 6.0, F # 4.0, TypeScript 1.5, Visual Studio Android simulator and other heavyweight development products.

Since the project has been upgraded to. NetFramework 4.6. 1, the development tool has shifted to VS 2015, so try C # 6.0. As a result, the online tutorial is not satisfactory, and it has not been updated for a long time, so I have to make a summary by myself.

1. Automatic property initialization (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 };
 
}

Read-only properties can also be initialized directly (C # 5.0 does not support it), or they can be initialized directly in the constructor

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

2. String embedded value (String interpolation)

In the previous version of String. Format as many parameters to write as many placeholders must also be in order, otherwise error. Parameter 1 more, so do the words really headache. In the new version of the string with $to identify the characters behind the use of {object} as placeholders. 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?" Hunky boy ":" Old fresh meat ")}");

If you want to output {or} symbols, just write two, such as $"{{".
Note the $sign, which is not available in many online N tutorials. It is "\ {account. Age\}", which has been abandoned in the new version.

3. Import static classes (Using Static)

As before, when using the static class Math, you need to import the System namespace before you can use it. Now you can import this static class directly, and then use its functions directly in your code.

using static System.Math;// Note that this is not a namespace 
 
Console.WriteLine($" Previous usage : {Math.Pow(4, 2)}");
Console.WriteLine($" You can use the method directly after importing : {Pow(4,2)}");

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

4. Null Value Operator (Null-conditional operators)

I have written countless such judgment codes before

if (*** != null)
{
     // Not for null Operation of
}
return null;

Using it now can simplify this way.

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.

5. Object Initializer (Index Initializers)

This method can be initialized by index assignment to dictionaries or other objects.

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:first
key: 2 value:second

6. Exception Filter (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, exceptions will continue to be thrown and the methods in catch will not be executed.

7. nameof expression (nameof expressions)

This is often written when checking method parameters:

private static void Add(Account account)
{
     if (account == null)
         throw new ArgumentNullException("account");
}

If the name of the parameter is changed one day, the following string is easily missed and forgotten to change.
After using the nameof expression, the compiler will check for the modified automatic navigation and refactoring (-_-! I don't know if the translation is correct.)

private static void Add(Account account)
{
     if (account == null)
         throw new ArgumentNullException(nameof(account));
}

8. Use await in cath and finally statement blocks (Await in catch and finally blocks)

This is not supported in c # 5.0.

Resource res = null;
try
{
    res = await Resource.OpenAsync( … );       // You could 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 Lambda expressions in attributes (Expression bodies on property-like function members)

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 added to C # 6.0 so far. There are no new functions, but more grammar sugar improvements. Development is more comfortable and faster.


Related articles: