[c#] fill an array in C#

In Java there are about 18 a static "fill" methods in the class Arrays that serve to assign one value to each element in an array. I'm looking for an equivalent in C# to achieve the same thing but I'm not finding anything with the same compactness:

1) ForEach as I understand passes elements in the array by value so I can't change them

2) Repeat from Enumerable creates a new array, it seems to be overhead to create a new array and then copy each element from the array

3) a for-loop isn't pretty, which I guess is why the Java folks introduced this compact notation to begin with

4) The Clear method from the Array class can set everything to zero, but then how do I convert zero to the non-zero value I want?

To demonstrate Java's syntax consider this code that prints three times the number 7:

int[] iii = {1, 2, 3};
Arrays.fill(iii, 7);
for (int i : iii) {
    System.out.println(i);
}

This question is related to c# arrays

The answer is


You could try something like this:

I have initialzed the array for having value 5, you could put your number similarly.

int[] arr = new int[10]; // your initial array

arr = arr.Select(i => 5).ToArray(); // array initialized to 5.

public static void Fill<T>(this IList<T> col, T value, int fromIndex, int toIndex)
{
    if (fromIndex > toIndex)
        throw new ArgumentOutOfRangeException("fromIndex");

    for (var i = fromIndex; i <= toIndex; i++)
        col[i] = value;
}

Something that works for all IList<T>s.


Say you want to fill with number 13.

int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();

or

List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();

if you prefer a list.


int[] arr = Enumerable.Repeat(42, 10000).ToArray();

I believe that this does the job :)


you could write an extension method

public static void Fill<T>(this T[] array, T value)
{
  for(int i = 0; i < array.Length; i++) 
  {
     array[i] = value;
  }
}