Is there a way to initialize all elements of an array to a constant value through generics?
+6
A:
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();
Vojislav Stojkovic
2009-01-23 19:21:06
+3
A:
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;
}
return ret;
}
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.
Jon Skeet
2009-01-23 19:29:37
shouldn't you return ret variable for the static method?
Igor Zelaya
2009-01-23 19:47:26
@Igor: Yup, fixed, thanks.
Jon Skeet
2009-01-23 20:08:44
+1
A:
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;
}
return array;
}
}
// now you can do this...
int[] array = new int[100];
array.FillWith( 42 );
Muad'Dib
2009-01-23 19:40:42
Great code snippet! +1. By the way you missed the static modifier on the method. I wish I could select more than one answer as correct :)
Igor Zelaya
2009-01-23 20:02:55
A couple of things - you've declared a return value, but not actually returned one (just like me!) and your example can be simplified to: int[] array = new int[100].FillWith(42);
Jon Skeet
2009-01-23 20:09:31
(I've fixed the public/static/return problems. Feel free to roll it back if you object to my messing around with it!)
Jon Skeet
2009-01-23 20:10:15