Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# ArrayList calling on a constructor class

I'm aware that an ArrayList is probably not the way to go with this particular situation, but humor me and help me lose this headache.

I have a constructor class like follows:

class Peoples
    {
        public string LastName;
        public string FirstName;
        public Peoples(string lastName, string firstName)
        {
            LastName = lastName;
            FirstName = firstName;
        }
    }

And I'm trying to build an ArrayList to build a collection by calling on this constructor. However, I can't seem to find a way to build the ArrayList properly when I use this constructor. I have figured it out with an Array, but not an ArrayList.

I have been messing with this to try to build my ArrayList:

ArrayList people = new ArrayList();
            people[0] = new Peoples("Bar", "Foo");
            people[1] = new Peoples("Quirk", "Baz");
            people[2] = new Peopls("Get", "Gad");

My indexing is apparently out of range according to the exception I get.

like image 282
EvanRyan Avatar asked Nov 29 '22 11:11

EvanRyan


1 Answers

It should be:

people.Add(new Peoples(etc.));

instead of

people[0] = new people()...;

Or better yet:

List<People> people = new List<People>();

people.Add(new People);

Just to be complete. Using a straight array:

People[] people = new People[3];

people[0] = new People();
like image 128
kemiller2002 Avatar answered Dec 04 '22 11:12

kemiller2002