none
How do I create a loop that creates multiple objects of a class? RRS feed

  • Question

  • (Is this even possible?) So (for example) I wanted a class called Fruit...

    class Fruit
    {
        private string _name;
        public string Name { get { return _name; } }
    }

    and I wanted to make a loop that created a bunch of these said "Fruits" like this (I know this wouldn't work like this but)...

    for (int i = o; i < 100; i++)
    {
        Fruit Apple<i> = new Fruit();
    }
    
    

    and I would hope that the names of these objects would come out like "Apple0", "Apple1", "Apple2"...

    So.  Is this even possible to do (in a different way of course) in c# or ANY programming language?

    Thanks.

    Tuesday, June 12, 2018 1:54 AM

All replies

  • Well,  the fruit object would have to be loaded into an array of fruit objects or a collection of fruit objects, a group of related objects that are accessible. Becuase otherwise,  what  is the point of being in a loop making objects?  

    https://www.c-sharpcorner.com/uploadfile/Ravish001/how-to-declare-an-array-of-custom-type/

    https://dzone.com/articles/different-ways-of-creating-list-of-objects-in-c

    collection access....

    foreach(var student in students)

    {

         var name = student.Name;

     }

    read or write....

     for (int i = 0; i < students.count(); i++)
    {
       
    var name = students[i].Name;

         students[i].Name = "help"}


    Tuesday, June 12, 2018 2:51 AM
  • You can do the multiple object creation, but the syntax would be a bit different than what you are thinking:

    Fruit[] Apple = new Fruit[100];
    for (int i = 0; i < 100; i++)
    {
        Apple[i] = new Fruit();
    }

    You can then access them as Apple[0], Apple[1], etc.

    Tuesday, June 12, 2018 6:39 AM
    Moderator
  • As long as your Fruit class lacks any set accessor, it won't work. Try:
    class Fruit
        {
            public string Name { get; set; }
        }
    
    
    public static void CreateFruits()
    {
        List<Fruit> fruits = new List<Fruit>();
        for (int i = 1; i < 5; i++)
        {
            string name = "fruit" + i.ToString();
            fruits.Add(
                new Fruit() { Name = name}
                );
        }
    
        fruits.ForEach(x => Console.WriteLine(x.Name));
    }
    
    
    wizend
    • Proposed as answer by Dolen Zhang Wednesday, June 13, 2018 2:32 AM
    Tuesday, June 12, 2018 8:23 AM