Good afternoon, I’m attempting to iterate over a set of objects to get every combination of touching objects. My code works as I’ve stepped through it in debug and the variable is being modified correct but the list i’m adding it to just doesn’t reflect the changes I see by the end of the code. By the end of the code, it contains a list of the same exact LinePiece object 25 times. (its all making sense now…)
I just did a more detailed look at the output of all my locals during the iteration and noticed that variable “word” (which is an object that holds a list of other objects, to represent a line of pieces) is indeed being properly modified each iteration and added to list “combos” which does indeed hold the correct version of “word” at the time, that is until next iteration when word changes (another piece is added to it) and is added to the list again, but when the new version of “word” is added, the previous list items of word change.
I understand classes are reference types and not value types in C#, similar to pointers and references in C++, so I think i know why this is happening, my question is what do I do to get the desired result of having new objects stored in the list instead of a reference to the same object 25 times.
Instead of adding references to the same object, I want “SNAPSHOTS” of waht the object was like during that iteration storing in the list of LinePieces…
I have a missing piece of knowledge in this area of C# and hope somebody can explain what I need to know.
Heres the code
List<LinePieces> combos = new List<LinePieces> ();
LinePieces word = new LinePieces ();
LinePieces searchRow = new LinePieces ();
foreach (LinePieces line in _board.Rows)
{
for(int x = 0; x <= _rows; x++)
{
searchRow.AddLine(line.Line.Where ((j, i) => (i >= x) == true ).ToList());
for (int y = 0; y < searchRow.Count; y++)
{
word.AddPiece(searchRow.Line[y]);
if (word.Count > 1)
combos.Add(word);
}
word = new LinePieces ();
searchRow = new LinePieces ();
}
}
