C# 9 is the latest version of the C# programming language and it introduces several new features and improvements that make it easier to write more concise, expressive and maintainable code. Some of the notable new features in C# 9 include:
- Records: C# 9 introduces a new type called records, which are lightweight classes that are designed for data modeling. Records automatically provide features such as immutability, equality and copy semantics.
Copy coderecord Person {
public string FirstName { get; init; }
public string LastName { get; init; }
}
- Init-only properties: C# 9 allows you to define properties that can only be set during object initialization, making it easy to create immutable types.
Copy codeclass Point {
public int X { get; init; }
public int Y { get; init; }
}
- Top-level statements: C# 9 allows you to use statements at the top level of a file, without requiring a class or method.
Copy codeusing System;
Console.WriteLine("Hello, World!");
- Target-typed new expressions: C# 9 allows you to use the „new“ keyword without specifying the type of the object being created.
Copy codevar point = new (1, 2);
- Improved pattern matching: C# 9 introduces several new pattern matching features, such as the „and“ pattern, the „or“ pattern, and the „not“ pattern.
Copy codeif (shape is not Circle)
{
// Do something
}
- Improved target-typed conditional expressions and null-coalescing expressions.
- Support for asynchronous streams.
- Improved support for immutable types with
init
setter.
C# 9 aims to simplify the language and reduce the amount of boilerplate code required, making it more productive and easier to work with. These new features should help to improve the developer experience while also increasing the expressiveness and maintainability of the code.