# C# --- 1. c# 6.0 2. C# 7.0 3. C# 7.1 4. C# 7.2 5. C# 7.3 6. C# 8.0 --- ## C# 6.0 ### Read-only auto-properties enable read-only types - Creating a public read/write property with a private backing field ```C# class Person { public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateOfBirth { get; set; } } class Person { public string FirstName { get; private set; } public string LastName { get; private set; } public DateTime DateOfBirth { get; private set; } public Person(string first, string last, DateTime birth) { this.FirstName = first; this.LastName = last; this.DateOfBirth = birth; } } ``` - C# readonly ```C# class Person { public string FirstName { get { return firstName; } } private readonly string firstName; public string LastName { get { return lastName; } } private readonly string lastName; public DateTime DateOfBirth { get { return dateOfBirth; } } private readonly DateTime dateOfBirth; public Person(string first, string last, DateTime birth) { this.firstName = first; this.lastName = last; this.dateOfBirth = birth; } } ``` - C# 6.0 - The backing field can be set through the property name, but only in a constructor. ```C# class Person { public string FirstName { get; } public string LastName { get; } public DateTime DateOfBirth { get; } public Person(string first, string last, DateTime birth) { this.FirstName = first; this.LastName = last; this.DateOfBirth = birth; } } ``` - [Example](https://docs.microsoft.com/en-ca/dotnet/csharp/tutorials/exploration/csharp-6?tutorial-step=1) --- ### Expression-bodied members ```c# public override string ToString() { return FirstName + " " + LastName; } ``` ```C# public override string ToString() => FirstName + " " + LastName; ``` ### A better string format --- ```C# public override string ToString() => $"{FirstName} {LastName}"; ``` --- ### Quick and easy null checks ```C# bool hasMore = s?.ToCharArray()?.GetEnumerator()?.MoveNext() ?? false; ``` --- ### Exception filters - 連線資料庫 ```C# using System; public class Program { public static void Main() { try { string s = null; Console.WriteLine(s.Length); } catch (Exception e) when (LogException(e)) { } Console.WriteLine("Exception must have been handled"); } private static bool LogException(Exception e) { Console.WriteLine($"\tIn the log routine. Caught {e.GetType()}"); Console.WriteLine($"\tMessage: {e.Message}"); return false; } } ``` --- # nameoF https://ithelp.ithome.com.tw/articles/10210675 --- https://docs.microsoft.com/zh-tw/dotnet/csharp/whats-new/csharp-8 http://www.informit.com/articles/article.aspx?p=2416187 https://docs.microsoft.com/zh-tw/dotnet/csharp/whats-new/csharp-6 ---