Built in way to construct array and each of its elements?

Viewed 51

Often I want to construct an array of reference types and then construct each element (and the array size isn't necessarily hard-coded), so I wrote a utility function to do it:

static TElem[] ConstructArray<TElem> (int length) where TElem : new() {
    TElem[] arr = new TElem[length];
    for (int k = 0; k < arr.Length; ++k)
        arr[k] = new TElem();
    return arr;
}

Example usage (runnable):

class Example {
    const int NumberOfLists = 3;
    List<int>[] listInit = ConstructArray<List<int>>(NumberOfLists);
}

My question is just: Does C# (8.0) have a built-in way to construct an array and then construct each of the elements, so that I can stop carrying that little utility function around?


Note: I'm not looking for this:

X[] array = new X[] { new X(), new X(), new X() };

That would negate the primary goal of convenience here.

1 Answers

If you don't mind using Linq, here's a handy one-liner:

MyClass[] arrcalc = 
    System.Linq.Enumerable.Range(0, count).Select(x => new MyClass()).ToArray();

There might be a better way using Linq, but this works just fine.

Related