1
Answer

Confused with ArrayList and Reference types

Simon

Simon

16y
2.8k
1
I have a custom object, EventList that extends ArrayList, and a second custom object, Event, that stores event information and has a constructor that can take a database ID to instantiate itself.

I am trying to write a method for the EventList to fill it with a list of Event objects instantiated from a database.

I am using the following loop


while (dbManager.DataReader.Read())
{                   
          int intEventID = (int) dbManager.DataReader["EventID"] ;
          this.Add(  new Event( intEventID )  );
}


However the this.Add(...) line seems to be updating a reference to the previously added Event Object rather than creating a new instance of an Event object. I am ending up with an array list with a number of references to the same Event object!

Can anyone shed any light on why this is happening, and how I can get around it?


Answers (1)