This post will discuss how to initialize all array elements with a specified value in C#.

We know that an array in C# is initialized with a default value on creation. The default value is 0 for integral types. If we need to initialize an array with a different value, we can use any of the following methods:

1. Using Enumerable.Repeat() method

We can use the Enumerable.Repeat() method in the System.Linq namespace to generate a sequence of a repeated value and then convert the sequence back to the array using the toArray() method. The following code example shows the usage of this method.

Download  Run Code

2. Using for loop

The recommended approach is to initialize an array is using a for-loop. The following code example demonstrates how to use a for-loop to fill an array with an initial value.

Download  Run Code

3. Using Array.Fill() method

The most simple approach is to use the Array.Fill() method, which internally uses a for-loop to fill an array with a single value.

Download  Run Code

That’s all about initializing all array elements with a specified value in C#.