The Spread Operator In C# 12
C# 12 introduces the spread operator (..), making it easier to merge collections.
For example, given two arrays:
int[] numbers1_CS12 = [ 1, 2, 3 ];
int[] numbers2_CS12 = [ 4, 5, 6 ];
You can merge them using:
int[] allItems = [ ..numbers1_CS12, ..numbers2_CS12 ];
This approach is more efficient than previous methods and minimizes memory allocations.
The spread operator can be combined with other array elements:
int[] join = [ ..a, ..b, ..c, 6, 5 ];
It also supports different collection types:
int[] a = [ 1, 2, 3 ];
Span<int> b = [ 2, 4, 5, 4, 4 ];
List<int> c = [ 4, 6, 6, 5 ];
List<int> join = [ ..a, ..b, ..c, 6, 5 ];
Even lists of tuples are easier to define and merge:
List<(string, int)> otherScores = [ ("Dave", 90), ("Bob", 80) ];
(string name, int score)[] scores = [ ("Alice", 90), ..otherScores, ("Charlie", 70) ];
These features in C# 12 make your code cleaner, more efficient, and more readable. Dive in and explore the new possibilities!