1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A little clunky, but not bad. I was wondering how to get a sized IEnumerable from scratch, didn't realize Enumerable.Range was a thing.

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.