I've got a bit of code that I've been working on for a friend for the past few days. At a high level it parses a text file and writes to an MDB. To cut a long story short, I've got a nested couple of loops doing some processing on the items. The inner loop only gets called in certain cases, but when it does, it's doing some strange things.
ArrayList CaseRecordItems = new ArrayList(); // this is created earlier
string baseTif = "sometext_"; // this is created earlier
CaseRecord cr = new CaseRecord(); (this gets populated with "stuff")
char increment = 'A';
for (int i = 0; i < FirstNames.Count; i++)
{
cr.Firstname = (string)FirstNames[i];
cr.Lastname = (string)LastNames[i];
if (FirstNames.Count > 1)
{
cr.Tif = baseTif + increment.ToString();
increment++;
}
CaseRecordItems.Add(cr);
}
The loop runs for example two times and should set the value of cr.Tif to sometext_A and sometext_B. This works correctly, but once the second item is added to the collection, the value of the first is changed to match it.
I suspect this is due to a lack of my understanding how these objects are being instantiated and passed around. Any insight would be appreciated.
EDIT:
Based on the awesome feedback (and my numb-nutzery) the issue has been resolved. Thanks to Dan's answer I made a couple of changes to the code that I had tried before utilizing the clone function (yes, beach I had actually tried that :P).
The new block looks like this: ArrayList CaseRecordItems = new ArrayList(); // this is created earlier string baseTif = "sometext_"; // this is created earlier CaseRecord cr = new CaseRecord(); // this gets populated with "stuff") char increment = 'A';
for (int i = 0; i < FirstNames.Count; i++)
{
CaseRecord cr2 = new CaseRecord();
cr2 = cr.Clone(); // preserves the data from outside
cr2.Firstname = (string)FirstNames[i];
cr2.Lastname = (string)LastNames[i];
if (FirstNames.Count > 1)
{
cr2.Tif = baseTif + increment.ToString();
increment++;
}
CaseRecordItems.Add(cr2);
}
Thanks everyone for the super-quick responses!