tags:

views:

292

answers:

3

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
+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
shouldn't you return ret variable for the static method?
Igor Zelaya
@Igor: Yup, fixed, thanks.
Jon Skeet
+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
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
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!)
Jon Skeet
i dont mind. feel free. :-)
Muad'Dib