Creating a list filled with new instances of an object

Not sure what is wrong with a for loop in this case. At the very least, we can presize the capacity of the list. That might not be important for 100 objects, but the size is arbitrary.

public class MyClass
{
    static int Capacity = 100;
    static List<MyObj> MyObjs = new List<MyObj>(Capacity);

    static MyClass() {
       for( var i = 0; i < Capacity; i++ ) {
          MyObjs.Add(new MyObj());
       }
    }
}

Apparently, the answer is "no". Thanks, everyone!


Edited to reflect that this method does not work.

I was curious about your comment about Enumerable.Repeat, so I tried it.

//do not use!
List<object> myList = Enumerable.Repeat(new object(), 100).ToList();

I confirmed that they do all share the same reference like the OP mentioned.


This wouldn't be hard to implement as an iterator:

IEnumerable<T> CreateItems<T> (int count) where T : new() {
    return CreateItems(count, () => new T());
}

IEnumerable<T> CreateItems<T> (int count, Func<T> creator) {
    for (int i = 0; i < count; i++) {
        yield return creator();
    }
}

Tags:

C#

Linq

List