Collection expressions in C# 12
Collection expressions in C# 12 are a new feature that simplifies the initialization of collection types. With collection expressions, you can directly initialize collections such as lists, dictionaries, and arrays with the values you want, without the need for explicit constructors or method calls.
This feature allows you to write more concise and readable code when working with collections. It eliminates the need for repetitive initialization code, making your code more efficient and easier to maintain. Here are some of the samples. Also note that ‘var’ cannot be used when declaring collections with the expressions.
//Before
var names = new List<string> { "bill", "steve", "mark", "elon" }
//After
string[] names = ["bill", "steve", "mark", "elon"];
//Before
var numbers = new List<int> { 1, 2, 3, 4, 5 };
//After
int[] numbers = [1, 2, 3, 4, 5];
The new syntax is much cooler and allows you to use the spread element, as shown below.
string[] names1 = ["bill", "steve", "mark", "elon"];
string[] names2 = ["bill", "steve", "mark", "elon"];
List<string> allNames = [..names1, ..names2];
Start utilizing these features to enhance the readability and elegance of your code.