C# 12 features: Collection expressions

Part 2 of a C# 12 series explaining collection expressions, including how [] initialization works across arrays and other collection types with practical examples.

.NET

Part 2 in a series on new language features in C# 12.

C# logo

Collection expressions

You can now use square brackets [] to initialise a collection! Usually square brackets indicate an array, but the collection expression can be assigned to other collection types too.

You can use them to assign values to fields or in method bodies.

private List<int> numbersList = [1, 2, 3, 4, 5];

Like primary constructors, I’ve also found these quite useful in new .NET 8 projects.

Further reading

https://learn.microsoft.com/dotnet/csharp/language-reference/operators/collection-expressions?WT.mc_id=DOP-MVP-5001655

Example source

https://github.com/flcdrg/csharp-12/blob/main/02-collection-expressions/CollectionExpressions.cs