C# 12.0 introduced .. and its terminology is a bit confusing, some call it Spread Element and some call it Spread Operator.
Before going through the correct terminology, first, let's see what it does.
IEnumerable<string> sweetFruits = ["Apple", "Banana", "Mango", "Pineapple"];
IEnumerable<string> sourFruits = ["Orange", "Grapefruit", "Lemon", "Lime"];
IEnumerable<string> fruits = [.. sweetFruits, .. sourFruits];
// Output: Apple, Banana, Mango, Pineapple, Orange, Grapefruit, Lemon, Lime
Here .. is spreading the elements in a collection. We are spreading the sweetFruits and sourFruits, and then combining those to create fruits.
And we can use this feature in different ways.
For an example consider this.
IEnumerable<Employee> employees =
[
new Employee("John Doe", "Contract"),
new Employee("Jane Doe", "Permanent")
];
List<Employee> permanentEmployees = employees
.Where(e => e.Type == "Permanent")
.ToList();
We can use .. and filter permanentEmployees as follows and not do .ToList().
List<Employee> permanentEmployees =
[
.. employees.Where(e => e.Type == "Permanent")
];
Now what do we call it?
There is a nice explanation given in this post:
.NET Blog: Refactor your code with C# collection expressions
Spread Element |
Jaliya