If I do the following:
List<GenericClass> listObj = new List<GenericClass>(100);
// Do I need this part too?
for (int i = 0; i < 100; i++)
{
listObj[i] = new GenericClass();
}
Basically I am asking if the C# compiler will automatically fire the GenericClass constructor for each of the 100 GenericClass objects in the list. I searched in the MSDN documentation as well as here on StackOverflow.
Thanks for any help.
Since you cannot do it directly with List you can use a helper method to have a generator and use the List(IEnumerable collection) overload.
This does work but it is not so pretty as it could be if List would support this functionality out of the box. The example program will print 100 lines consisting of 5 a characters.
That's not how
List
works. When you specify a capacity, it's an initial capacity, not the number of items in the list. The list contains no elements until you add them via theAdd
method. Lists do not have a maximum capacity. And since you're adding objects via the Add method, yes, you would have to new them up first.In fact, doing what you put in your question would throw an
ArgumentOutOfRange
exception.For what you're doing, you'd need to use an array.
This will work:
This is what you were attempting to do:
Yes you do need to create and add each instance to the list. Take a look at the remarks section for this constructor style: http://msdn.microsoft.com/en-us/library/dw8e0z9z.aspx
You are specifying how many elements you expect to put in the list so that the list does not have to resize behind the scenes every time you add a new GenericClass instance to it.
No! It specify the initial capacity.
MSDN article: