2

Is there a way to initialize all elements of an array to a constant value through generics?

3 Answers 3

7

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();
Sign up to request clarification or add additional context in comments.

Comments

4

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

shouldn't you return ret variable for the static method?
2

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

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 :)
You also mean "extension method" rather than "extender".
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);
(I've fixed the public/static/return problems. Feel free to roll it back if you object to my messing around with it!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.