C# 9 has the following updates:
-
Enhancements to pattern matching, including new logical operators, new is expressions, new switch expressions, and more.
-
The new init-only attribute, which enables attributes to be assigned only at initialization time.
-
New record types that can be used to quickly create immutable objects.
-
Function members can be top-level statements and need not be defined in a class.
-
New with expression that can be used to create new record types based on existing record types.
-
New syntax for lambda expressions, including more concise parameter lists and more flexible type inference.
-
New type inference syntax, including var and target-typed new expressions.
-
Support for async streams and async enumerables.
Reflected in the code:
- Enhancements to pattern matching:
-
// 新的逻辑运算符 if (a is 1 or 2) { ... } // 新的 is 表达式 if (obj is string s) { ... } // 新的 switch 表达式 string result = myValue switch { "a" => "A", "b" => "B", "c" => "C", _ => "unknown" };
- New init-only attribute:
-
public class Person { public string Name { get; init; } public int Age { get; init; } } var person = new Person { Name = "John", Age = 30 }; person.Age = 40; // 编译错误
- New record type:
-
public record Person(string Name, int Age); var person = new Person("John", 30); var newPerson = person with { Age = 40 };
- Function members can be top-level statements:
-
using System; Console.WriteLine("Hello, world!");
- New with expression:
-
var person = new Person("John", 30); var newPerson = person with { Age = 40 };
- Syntax for the new Lambda expressions:
-
// 更简洁的参数列表 (int x, int y) => x + y // 更灵活的类型推断 (int x, _) => x
- New type inference syntax:
-
// var var person = new Person("John", 30); // target-typed new 表达式 Person person = new("John", 30);
- Asynchronous streams and asynchronous enumerables are supported:
-
async IAsyncEnumerable<int> GenerateNumbersAsync() { for (int i = 0; i < 10; i++) { await Task.Delay(100); yield return i; } } await foreach (var number in GenerateNumbersAsync()) { Console.WriteLine(number); }