Array initialization with default constructor
Solution 1:
You can't, basically. When you create an array, it's always initially populated with the default value for the type - which for a class is always a null reference. For int
it's 0, for bool
it's false, etc.
(If you use an array initializer, that will create the "empty" array and then populate it with the values you've specified, of course.)
There are various ways of populating the array by calling the constructor - I would probably just use a foreach loop myself. Using LINQ with Enumerable.Range/Repeat feels a little forced.
Of course, you could always write your own population method, even as an extension method:
public static T[] Populate<T>(this T[] array, Func<T> provider)
{
for (int i = 0; i < array.Length; i++)
{
array[i] = provider();
}
return array;
}
Then you could use:
Sample[] samples = new Sample[100].Populate(() => new Sample());
What I like about this solution:
- It's still a single expression, which can be useful in various scenarios
- It doesn't introduce concepts you don't actually want (like repeating a single value or creating a range)
Of course you could add more options:
- An overload which takes a
Func<int, T>
instead of aFunc<T>
, passing the index to the provider - A non-extension method which creates the array and populates it
Solution 2:
Your code creates only the array, but neither of its items. Basically, you need to store instances of Sample
into this array.
To put it simple, without any fancy LINQ etc.:
Sample[] samples = new Sample[100];
for (int i = 0; i < samples.Length; i++) samples[i] = new Sample();
Please also note your solution is not thread-safe.
Solution 3:
There is no way to do this automatically; array initialization is essentially "wipe this block of memory to 0s". You would have to do something like:
var arr = new SomeType[size];
for(int i = 0 ; i < size ; i++) arr[i] = new SomeType();
Solution 4:
At this point you have an empty array of size 100, if you want to fill it with items, then you would have to do something like:
for(int i=0; i<samples.Length; i++) {
samples[i] = new Sample();
}
Solution 5:
The problem is that by declaring that array, you never allocated space for each object. You merely allocated space for 100 objects of type Sample. You'll have to call the constructor on each yourself.
To elaborate:
Food[] foods = Food[100];
for (int k = 0; k < foods.length; k++) {
foods[k] = new Food();
}
An interesting work around might be a factory function. Consider attaching this to your Sample class.
public static Sample[] getInstances(int aNumber) {
Sample[] sample = Sample[aNumber];
for (int k = 0; k < sample.length; k++) {
sample[k] = new Sample();
}
return sample;
}
Hides the blemish, a bit - providing this is a useful function to you.