Caillou
Caillou

Reputation: 9

How do you make multiple instances from a class into an array with a loop in C#

I want the user to be able to specify the number of instances there are. I find that a good way to do this is using a for loop.

    class Instance
    {
        public string name;
        public int health;
        public int dmg;

        public Instance()
        {
            name = Instance;
            health = 100;
            dmg = 10;
        }


class Program {

  static void Main(string[] args) {
    instance[] instanceArray = new instance

    Console.WriteLine("how many instances will there be?");
    string inp = Console.ReadLine();

    for (int i = 0; i >= inp; i++) {
      //TODO: I don't know what would go in here
    }
  }
}

Upvotes: 0

Views: 805

Answers (2)

Ran Turner
Ran Turner

Reputation: 18036

You can use Enumerable.Range for that:

instance[] instanceArray = Enumerable.Range(0, inp).Select(i => new instance()).ToArray();

Or just initiate the Objects via the loop like you started doing:

instance[] instanceArray = new instance[inp];
for (int i=0; i<inp ;++i){
  instance[i] = new instance(); 
}

Upvotes: 1

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186708

You should create an instance in the for loop and assign it to array's item:

static void Main(string[] args) {
  // In case of array, you should specify its length beforehead
  // So, let's ask user about the number of instances to create
  Console.WriteLine("how many instances will there be?");

  // Note, int imp (not string): number of instances must be integer
  // like 3, 5, 8, not string as "bla-bla-bla"
  //TODO: int.TryParse is a better approach
  int inp = int.Parse(Console.ReadLine());

  // We create an array to hold inp instances
  instance[] instanceArray = new instance[inp];

  // Time to create inp instances and put them to array:
  for (int i = 0; i < inp; i++) {
    // Create an instance and assign it to i-th item:
    instance[i] = new Instance();    
  }

  // from now you have instance array with inp items 
}

A bit shorter way to create the same array is Linq:

using System.Linq;

...

instance[] instanceArray = Enumerable
  .Range(1, inp)
  .Select(_ => new Instance())
  .ToArray(); 

Upvotes: 1

Related Questions