Initialize all elements of an array with a given value in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System; using System.Linq; public class Example { public static void Main() { int element = 1; int count = 10; int[] array = Enumerable.Repeat(element, count).ToArray(); Console.WriteLine(String.Join(",", array)); } } /* Output: 1,1,1,1,1,1,1,1,1,1 */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Example { public static void Main() { int element = 1; int count = 10; int[] array = new int[count]; for (int i = 0; i < count; i++) { array[i] = element; } Console.WriteLine(String.Join(",", array)); } } /* Output: 1,1,1,1,1,1,1,1,1,1 */ |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { public static void Main() { int element = 1; int count = 10; int[] array = new int[count]; Array.Fill(array, element); Console.WriteLine(String.Join(",", array)); } } /* Output: 1,1,1,1,1,1,1,1,1,1 */ |
That’s all about initializing all array elements with a specified value in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)