C# 12: Introducing the spread operator on collections
Introduction
.NET 8 and C# 12 are available in preview and I’m glad to share with you with a new feature that comes from Javascript: The spread operator. As a reminder, in Javascript, the spread operator, which takes the form of suspension points: … allows you to make copies of variables in no time at all. The original variable and its copy are totally independent. We can easily modify one without modifying the other! In C#, it’s the same thing, although collections are reference types!
Example
According to the Microsoft doc (https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-12#collection-expressions), as long as the type represent a Collection in C# (+ Spans) you can use it on them, Generic Collections and Non-Generic Collections.
Here is a bunch of examples:
Note: I haven’t been able to make it work with a Dictionary or Multidimensional arrays, I have sent an email to the Microsoft team and I will keep you poste when I get their answer.
Update! Dictionaries and Multidimensional arrays are not supported yet in C# 12: https://github.com/markjprice/cs12dotnet8/blob/main/docs/errata/improvements.md#page-457—initializing-collections-using-collection-expressions. It will probably be available in a future update or even in C# 13, here is the specification: https://github.com/dotnet/csharplang/blob/main/proposals/collection-expressions-next.md#natural-type.
Enjoy 🙂