public class Sample
{
static int count = 0;
public int abc;
public Sample()
{
abc = ++Sample.count;
}
}
I want to create an array of above class, and want each element in the array to be initialized by invoking the default constructor, so that each element can have different abc
.So I did this:
Sample[] samples = new Sample[100];
But this doesn't do what I think it should do. It seems this way the default constructor is not getting called. How to invoke default constructor when creating an array?
I also would like to know what does the above statement do?
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.:
Please also note your solution is not thread-safe.
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:
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, forbool
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:
Then you could use:
What I like about this solution:
Of course you could add more options:
Func<int, T>
instead of aFunc<T>
, passing the index to the providerThe 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:
An interesting work around might be a factory function. Consider attaching this to your Sample class.
Hides the blemish, a bit - providing this is a useful function to you.
Here is another one-liner that doesn't require any extension method:
Another nice option is Scott's suggestion to Jon's answer:
So you can do:
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: