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.