2

Can I initialize an array of classes with an default constructor (or even better, an specified one) without going through a loop?

So, let's say I have an array of Person:

var arr = new Person[10];

Now, I should initialize each Person by looping through all of them.

foreach(var p in arr)
    p = new Person();

Can I avoid the loop?

2
  • 3
    Take a look at this answer from @JonSkeet Commented Apr 26, 2013 at 18:49
  • Note that your loop wouldn't compile, but we take your point. (Assigning to the loop variable won't work, you'd need a 'for' loop or something equivalent.) Commented Apr 26, 2013 at 18:51

2 Answers 2

2

For an arbitrary sized array, you really can't avoid the loop. You can do something like this:

Enumerable.Range(0,10).Select(i=>new Person()).ToArray();

but that uses a loop underneat as well.

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

Comments

0
var arr = new Person[] {new Person(),new Person()...};

2 Comments

For medium to big arrays, this look even worse than a loop honestly.
@Pierre-LucPineault not contesting that, the question was how to avoid the loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.