Is there a way to initialize all elements of an array to a constant value through generics?
3 Answers
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.
1 Comment
Igor Zelaya
shouldn't you return ret variable for the static method?
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 );
4 Comments
Igor Zelaya
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 :)
Jon Skeet
You also mean "extension method" rather than "extender".
Jon Skeet
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
(I've fixed the public/static/return problems. Feel free to roll it back if you object to my messing around with it!)