views:

51

answers:

4

So here's my problem...

Let's say I have a simple "Person" class just with "FirstName" and "LastName" attributes.

I want to have a form where the user says how many "Persons" he wants to create and then he fills the name for each one.

E.g. user wants to create 20 persons... he puts 20 on a box clicks the button and starts writing names.

I don't know how many users he is going to create so I can't have hundreds of object variables in my code like this

Person p1;
Person p2;
(...)
Person p1000;
+2  A: 

You need to use a list. You create the list this vay:

var persons=new List<Person>();

and you can dinamically add items this way:

Person thePerson=new Person(...);
persons.Add(thePerson);
Konamiman
A: 

You'll probably want to use a collection to Person objects. Try looking at these links

Kane
+4  A: 

Just use a

List<Person> lstPersons = new List<Person>();

And then add persons to it with:

lstPersons.Add(new Person());

You can then access the persons with

lstPersons[0]
lstPersons[1]
...
Maximilian Mayerl
Thanks... It's pretty simple solution. My brain was complicating it.
Joao Heleno
It's worth noting that the problem the user describes doesn't require the use of a dynamic list over an array. Unless there are other requirements that necessitate a dynamic list, an array will be slightly more performant (although not to the point of being significant, so if you're more comfortable with lists than arrays go ahead).
Chris
Yes, you are right, but the performance overhead is negligible. I always like to use lists over arrays just because it saves me work if I would have to change it later. I think easy maintainance is more important than a few milliseconds better performance for a few thousand access to the list.
Maximilian Mayerl
+3  A: 

Create an array, sized to whatever number the user inputted. Then you can just loop through the array to instantiate them all.

int numberOfPeople = xxx; // Get this value from the user's input
Person[] people = new Person[numberOfPeople];
for (int i = 0; i < people.Length; i++)
    people[i] = new Person();
Chris