What’s new in C# 11
C# 11 is a programming language published by Microsoft and is constantly updated with innovations. Below I can list some of the innovations in C# 11:
1.
This property allows predetermining whether or not object type variables should be null. This provides more defense against null values in your code and aims to avoid errors.Nullable Reference Types:
2 3 |
string? name = null; // The '?' indicates that the variable can be null Console.WriteLine(name.Length); // This will cause a compile-time error, because name can be null |
2.
This feature allows you to asynchronously manage the stream. For example, you can process a database query result asynchronously and process the results in a loop.Async Streams:
2 3 4 5 6 7 8 9 10 11 12 13 14 |
public async IAsyncEnumerable<int> GetNumbersAsync() { for (int i = 0; i < 5; i++) { await Task.Delay(1000); yield return i; } } // The method can be used like this: await foreach (var number in GetNumbersAsync()) { Console.WriteLine(number); } |
3. Enhanced pattern matching:
This feature provides more features in pattern matching. For example, you can check the type of a variable or access an object’s properties.
2 3 4 5 6 |
object o = "hello"; if (o is string s && s.StartsWith("h")) { Console.WriteLine("The string starts with 'h'"); } |
4.
This property allows you to create properties that can only be initialized. These properties are marked as immutable and can only be set when the object is created.Init-only properties:
2 3 4 5 6 7 8 9 10 11 12 13 |
public class Person { public string FirstName { get; init; } public string LastName { get; init; } public Person(string firstName, string lastName) { FirstName = firstName; LastName = lastName; } } var person = new Person("John", "Doe"); person.FirstName = "Jane"; // This will cause a compile-time error, because FirstName is an init-only property |
Recent Comments