I have constructed the following simplistic example to illustrate the problem I'm having in my actual code, which is much more complex.
First, my simple classes:
public class InnerTemp {
public int A { get; set; }
public int B { get; set; }
public int C { get; set; }
}
public class OuterTemp {
public List<InnerTemp> InnerTemps { get; set; }
}
And the implementation:
var outerTemps = new List<OuterTemp>();
var innerTemps = new List<InnerTemp>();
innerTemps.Add(new InnerTemp() { A = 1, B = 2, C = 3 });
innerTemps.Add(new InnerTemp() { A = 4, B = 5, C = 6 });
for( int i = 1; i < 5; i++ ) {
foreach( InnerTemp innerTemp in innerTemps ) {
innerTemp.A += i;
innerTemp.B += i;
innerTemp.C += i;
}
var outerTemp = new OuterTemp()
{
InnerTemps = innerTemps
};
outerTemps.Add(outerTemp);
}
I set my breakpoint on the last line, the closing curly brace. On the first iteration, the value of outerTemps[0].InnerTemps[0].A
is 2, as expected. But on the 2nd loop, the value of outerTemps[0].InnerTemps[0].A
becomes 4, which is baffling me. The first object's property A is being stomped merely because another object was added. I fully expect outerTemps[1].InnerTemps[0].A
to be different, but why is my original property stomped?
How can I change this so that previous object properties don't get overwritten each time a new object is added to the collection?