I have a basic C# program to demonstrate this:
namespace ConsoleApp5
{
internal class Program
{
static void Main(string[] args)
{
List<int> list = [1, 2, 3, 4, 5, 6];
List<int> list2 = [.. list];
}
}
}
What is the name for the trick being used to initialize list2
?
2
They’re known as collection expressions, introduced in C# 12 / .NET 8:
A collection expression is a terse syntax that, when evaluated, can be assigned to many different collection types. A collection expression contains a sequence of elements between [ and ] brackets
The [.. list]
syntax is known as a spread element, it’s the same as inlining the entire list:
You use a spread element
..
to inline collection values in a collection expression.
It is called the Spread operator