I have a static public List of type BoxPair which I’m trying to write stuff to, but it changes every record every time I add a new entry into it. I’m hoping someone can see what’s going wrong here, as it’s driving me slightly insane. The full addition code is below:
public static List<BoxPair> CreateBoxPair (int iBoxCount)
{
SetTopBox primary;
SetTopBox backup;
for (int i = 0; i < iBoxCount; i++)
{
primary = new SetTopBox();
backup = new SetTopBox();
primary.IBoxNumber = i;
primary.SDeviceName = "Box" + (i + 1).ToString("00");
primary.Role = Box.ROLE_PRIMARY;
backup.IBoxNumber = i;
backup.SDeviceName = "Box" + (i + 1).ToString("00");
backup.Role = Role.ROLE_BACKUP;
lstBoxes.Add(new BoxPair(primary, Role));
lstBoxes.Add(new BoxPair(backup, Role));
foreach (BoxPair p in lstBoxes)
{
Declarations.BOXES.Add(p);
}
}
return lstBoxes;
}
I know it’s going to be something basic, but from what I can see, I’m always using a new primary/backup box, so nothing should conflict. Any ideas would be greatly appreciated.
Cheers.
P.S. Every post I make, SO removes the first word, so I have to type it twice. Any ideas as to why that happens?
EDIT: As all the approaches listed below have given the same result, I’m guessing that this is a problem that cannot be solved. Therefore, I’m returning to the drawing board to try and approach this differently. Thanks for all the help, anyways, chaps 🙂
From the comments my best bet on code that works is as follows:
I think there are two issues in the original code:
primaryandbackupbeing declared outside the loop.foreachloop inside the loop adding the entries to the other collection multiple times.