I created an object called Participant.
Now I want to have an array of my Participant objects so that I could show them in a datagrid.
Here are the codes I tried (for better understanding of the problem, I removed the loops and datagrid codes):
Participant[] list = new Participant[count];
Participant one = new Participant(name, address);
Participant two = new Participant(name2, address2);
list[0] = one;
list[1] = two;
However, when I get values of one participant like through a messagebox in this manner,
MessageBox.Show(list[0].getName());
all it reflects are the data of participant two. Same is true if I have 3 objects, all it reflects is the data last sent into the array.
I know it is possible to have array of objects so there must be something I’m doing wrong. Or is there a better way to do this?
With the code as presented, the only way I can think of causing that is if the backig field (in
Participant) was declared “static“. If so, remove the “static“.Otherwise; does the actual code do a “
new” for the two objects? Or does it overwrite an object after adding it to the array? (which means you have the same object twice in the array).I would expect
ReferenceEquals(list[0], list[1])to be false in a sane world – can you test this and let us know?Final thought; is there a “
foreach” in the real code? It could be the infamous captured variable problem…