Some new features of C# 9

C# 9 has the following updates:

  1. Enhancements to pattern matching, including new logical operators, new is expressions, new switch expressions, and more.

  2. The new init-only attribute, which enables attributes to be assigned only at initialization time.

  3. New record types that can be used to quickly create immutable objects.

  4. Function members can be top-level statements and need not be defined in a class.

  5. New with expression that can be used to create new record types based on existing record types.

  6. New syntax for lambda expressions, including more concise parameter lists and more flexible type inference.

  7. New type inference syntax, including var and target-typed new expressions.

  8. Support for async streams and async enumerables.

Reflected in the code:

  1. Enhancements to pattern matching:
  2. // 新的逻辑运算符
    if (a is 1 or 2) { ... } 
    
    // 新的 is 表达式
    if (obj is string s) { ... }
    
    // 新的 switch 表达式
    string result = myValue switch {
        "a" => "A",
        "b" => "B",
        "c" => "C",
        _ => "unknown"
    };
    
  3. New init-only attribute:
  4. public class Person
    {
        public string Name { get; init; }
        public int Age { get; init; }
    }
    
    var person = new Person { Name = "John", Age = 30 };
    person.Age = 40; // 编译错误
    
  5. New record type:
  6. public record Person(string Name, int Age);
    
    var person = new Person("John", 30);
    var newPerson = person with { Age = 40 };
    
  7. Function members can be top-level statements:
  8. using System;
    
    Console.WriteLine("Hello, world!");
    

  9. New with expression:
  10. var person = new Person("John", 30);
    var newPerson = person with { Age = 40 };
    
  11. Syntax for the new Lambda expressions:

  1. // 更简洁的参数列表
    (int x, int y) => x + y
    
    // 更灵活的类型推断
    (int x, _) => x
    

  2. New type inference syntax:
  3. // var
    var person = new Person("John", 30);
    
    // target-typed new 表达式
    Person person = new("John", 30);
    

  4. Asynchronous streams and asynchronous enumerables are supported:
  5. 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);
    }
    

Guess you like

Origin blog.csdn.net/JianShengShuaiest/article/details/130963585