Skip to content

Create multiple instances of a class in a loop

mgroesink

Asked Oct 8, 2004, 6:49 AM EDT3 answers
Share
LinkedInX
In C# I create a class and from within a form I want to create multiple instances of that class in a loop. Suppose the name of the class is Emp. I know this doesn't work, but what is the way to fix this? for (int x=0 ; x<10 ; x++) { Emp "Emp" + x.ToString(x) = new Emp() } The problem is that I cannot use a string as above, but how do I give all of the new objects a unique name? And how can I access the newly created objects? Anyone there to help me? Thanks in advance. Marcel Roesink

3 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • +1
    When using ArrayList you are forced to cast the objects when retrieveing them from the ArrayList wich can result in very ugly code and misscasts. I suggest (if you know how many classes are needed) to stick with an regular array. Emp[] emp = new Emp[10]; for(int i = 0; i < emp.Length; i++) { emp[i] = new Emp(); }
    +1
  • 0
    There are several ways. I would use an ArrayList (under Collection namespace). /********************************************************/ ArrayList MyObjectCollection = new ArrayList(); for (x=0;x<10;x++) { MyObject newObject = new MyObject(); MyObjectCollection.Add(newObject); } /********************************************************/ You cab access the object as in an array (Actualy it is an array)- there is also a way to make it a hashtable - search in google.
    0
  • 0
    How can you run each instance of the class in its own thread? All instances must run at the same time.
    0