Tuesday, May 14, 2024

C# 12.0: .. Spread Element or Spread Operator

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
I personally agree with the explanation and even the feature specification uses the term Spread Element. But there are some places in official .NET documentation (like here: C# 12: Collection Expressions) that refer .. as Spread Operator.

Hopefully, we can get this terminology consistent across.

Hope this helps.

Happy Coding.

Regards,
Jaliya


Update 15/05/2024:

Reached out to .NET team and they are already in the process of addressing inconsistencies, both in the feature spec and the docs. It is going to be called the Spread Element and not Spread Operator.

Also, note that .. is used in three different places in the language: in collection expressions to indicate a spread element, in list patterns to indicate a slice pattern and as the range operator. The only location where it’s an operator is the range operator.

No comments:

Post a Comment