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.
That’s not how
Listworks. 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 theAddmethod. 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
ArgumentOutOfRangeexception.For what you’re doing, you’d need to use an array.
This will work:
This is what you were attempting to do: