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?

MBZ
  • 26,084
  • 47
  • 114
  • 191
  • 3
    Take a look at this [answer](http://stackoverflow.com/questions/4839470/array-initialization-with-default-constructor) from @JonSkeet – Cacho Santa Apr 26 '13 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.) – Anthony Pegram Apr 26 '13 at 18:51

2 Answers2

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.

Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
0
var arr = new Person[] {new Person(),new Person()...};
Brian Dishaw
  • 5,767
  • 34
  • 49
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151