This is a follow-up post to C# 12 Primary Constructors. Like that article, this one originates from the preparation notes for my presentation at the ABP Dotnet Conference 2024.
I love collection expressions. Like primary constructors, collection expressions will see a significant adoption in the long run.
Collection expressions introduce a new way to initialize common collection values in a terse, unified syntax.
This is how we initialize collections today:
var x1 = new int[] { 1, 2, 3, 4 }; var x2 = Array.Empty<int>(); WriteByteArray(new[] { (byte)1, (byte)2, (byte)3 }); List<int> x3 = new() { 1, 2, 3, 4 }; Span<DateTime> dates = stackalloc DateTime[] { GetDate(0), GetDate(1) }; WriteByteSpan(stackalloc[] { (byte)1, (byte)2, (byte)3 }); Notice how the code is diverse depending on the type and the context. It is also verbose. Look at how we initialize an empty int array (second line); it’s lengthy and starkly contrasts with the previous line, where we initialize the same type with some actual values. In many situations, casting is needed; again, take a look at the WriteByteArray and WriteByteSpan calls.
...