Source code
.NET Best Practices C# Visual Studio

How to Use Spread Operators in C# 12.0

Welcome to today’s post.

In today’s post I will be showing you how to use another new feature in C# 12.

I will be showing you how to use the Spread operator.

In a previous post, I showed you how to use Collection Expressions. I will be making use of collection expressions in this post to help us make efficient use of the Spread operator.

Before I define the spread operator and how it is used, I will look at another method in C# that allows us to combine two lists.

Any list that we define in C# is a collection of items that is enumerable.

One of the ways in which we can define a list of integers in C#, is to use a Collection Expression. Below is a list of five integers:

int[] ratings = [1, 2, 3, 4, 5]; 

If we wanted to define a list of ratings to represent lower, middle, or high ratings. Below are the definitions for these ratings:

int[] low_ratings = [1, 2, 3, 4]; 
int[] medium_ratings = [5, 6, 7]; 
int[] high_ratings = [8, 9, 10]; 

In the next section, I will show how to concatenate two lists using an enumerable class.

Using the IEnumerable Concat() Method

If we want to combine the above ratings lists into one list, we can use the Concat() method of the IEnumerable class. This method takes two parameters as shown:

public static System.Collections.Generic.IEnumerable<TSource> Concat<TSource> (this System.Collections.Generic.IEnumerable<TSource> first, System.Collections.Generic.IEnumerable<TSource> second);

An example of how we use Concat() is shown below:

int[] low_ratings = [1, 2, 3, 4];
int[] medium_ratings = [5, 6, 7];
int[] high_ratings = [8, 9, 10];

Note that we are starting with defining the lists as integer arrays. The reason for this is that starting with collection expressions means that they are an also an enumerable type which can also be concatenated.

What we do next is to concatenate the low and medium ratings to give an intermediate collection:

int[] intermediate_ratings = low_ratings.Concat(medium_ratings);

After we have applied the concatenation operator, to end up with an array type, we used the ToArray() extension method to convert the intermediate IEnumerable<int> type to an int[] type.

The above results in the following list:

[1, 2, 3, 4, 5, 6, 7]

To complete the concatenation of all sub-lists, we apply the same concatenation to the final sub-list:

int[] all_ratings = intermediate_ratings.Concat(high_ratings).ToArray();

The above results in the following list:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The above seems like a lot of effort to concatenate three smaller arrays into one final array. We can improve the efficiency even more. Did you know that the Concat() method can be chained? This just means that we can re-apply the Concat() method to an existing IEnumerable<int> instance to result in another IEnumerable<int> instance.

We just remove the intermediate array variable and combine the first concatenation with the second concatenation as shown:

Int[] all_ratings = low_ratings
 			.Concat(medium_ratings)
 			.Concat(high_ratings)
 			.ToArray();

The above results in the following list:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The outcome is the same, whether we use intermediate results or chaining.

Output from the debugger showing the concatenations resulting in an array is below:

In the next section, I will show how to use the spread method.

Defining the Spread Method

As we have seen, using the Concat() method is one way to combine multiple collections into one collection. However, there is another way to achieve the same outcome.

This is to use what is known as a Spread. A spread is an operator that includes arrays into a larger array to produce a resulting larger array that combines the smaller arrays.

The Spread operator is denoted by the ellipsis:

In a typical spread operation that combines the three arrays a, b, c to produce a larger array d, we have:

int d[] = [ .. a, .. b, .. c ];

We must include a space between the ellipsis and the list variable we are including in the larger, new array like this:

Applying the spread operator to the previous ratings lists we concatenated earlier we can achieve the same outcome.

I will show an example of how this is done in the next section.

Example Usage of the Spread Method

An example of how to use the spread method is shown below:

int[] all_ratings_spread = [.. low_ratings, .. medium_ratings, .. high_ratings];

As the resulting collection is enumerable, we can iterate and output the elements in the collection:

OutputNumericList("Combined ratings list (spread)", all_ratings_spread);
..

static void OutputNumericList(string description, int[] ratings)
{
    Console.WriteLine(description);

    foreach (int val in ratings)
    {
        Console.WriteLine(val);
    }
}

The output for the combined collection is unchanged from the concatenation method, and is still:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Output from the debugger showing the spreads resulting in an array is below:

Another thing to remember, is that the concatenation and spread operators do not perform a set union on the entries in each sub-array. Overlapping entries across the arrays are included in the final combined array.

Borrowing the Idea from TypeScript and JavaScript

The spread operator is nothing new in programming syntax. It has already been in use in the JavaScript (ES6) and TypeScript scripting languages.

An example of how it is used in JavaScript is shown below:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combo_array = [ …array1, …array2 ]; 

Note the difference between the Spread operator used in JavaScript/TypeScript and C# 12: The extra full-stop character is included in the ellipsis as shown:

…array1

In JavaScript and TypeScript, we can apply the spread operator to arrays and objects. It is an extremely useful part of the developer toolkit when it comes to allocating and manipulating arrays, which can be a pain to keep developing utilities to achieve an important part of array manipulation.

We have seen two approaches in combining arrays into one larger, unified array. The concatenation method that we are more accustomed to, or the newer, more recent approach using the spread operator, that can be applied to an array defined as an expression collection or as an allocated array.

That is all for today’s post.

I hope you have found this post useful and informative.

Social media & sharing icons powered by UltimatelySocial