Is there a way to initialize all elements of an array to a constant value through generics?
I would use an extender (.net 3.5 feature)
public static class Extenders
public static T FillWith<T>( this T array, T value )
for(int i = 0; i < array.Length; i++)
array[i] = value;
// now you can do this...
int array = new int;
array.FillWith( 42 );
Personally, I would use a good, old for loop, but if you want a one-liner, here it is:
T array = Enumerable.Repeat(yourConstValue, 100).ToArray();
If you need to do this often, you can easily write a static method:
public static T FilledArray<T>(T value, int count)
T ret = new T[count];
for (int i=0; i < count; i++)
ret[i] = value;
The nice thing about this is you get type inference:
string foos = FilledArray("foo", 100);
This is more efficient than the (otherwise neat) Enumerable.Repeat(...).ToArray() answer. The difference won't be much in small cases, but could be significant for larger counts.