fill an array in C#
arrays, c#
Solution
Write yourself an extension method
public static class ArrayExtensions {
public static void Fill<T>(this T[] originalArray, T with) {
for(int i = 0; i < originalArray.Length; i++){
originalArray[i] = with;
}
}
}
and use it like
int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);
will fill all the elements with 13
Problem
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); } ```