Conor Watson
Conor Watson

Reputation: 617

Why does this List<T> update when I modify a separate variable?

So I'm currently writing a function to load some data from a folder of text files.

public void loadPatterns()
{
    string[] files = Directory.GetFiles("patterns/");
    Level pattern = new Level();
    List<char> row = new List<char>();
    List<List<char>> grid = new List<List<char>>();

    for(int i = 0; i < files.Length; i++)
    {
        var lines = File.ReadLines(files[i]);
        foreach(string line in lines)
        {
            foreach(char c in line)
            {
                row.Add(c);
            }
            grid.Add(row);
            row.Clear();
        }
        pattern.grid = grid;
        patterns.Add(pattern);
        grid.Clear();
    }
}

However at the moment once the foreach(string line in lines) loop finishes, the grid has a number of rows that are completely empty. After looking through the debugger, it seems that even after a single row has been added to the grid, the row.Clear() method will clear the data that has been added to the List as well as clearing the data in the local variable 'row'.

Why does this happen?

I'm primarily a C++ programmer, so apologies if I've missed something very obvious for someone more familiar with C#.

Upvotes: 2

Views: 68

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109567

When you call grid.Add(row); you are not adding a copy of the row to the grid. You are adding a reference to the row. Therefore, when you call row.Clear() you are clearing the row that is stored inside the grid.

To fix this, you need to create a new row for each row of the grid. To do that, move the declaration of row to just after foreach(string line in lines):

 foreach(string line in lines)
 {
     var row = new List<char>();
     ...

Upvotes: 3

Nico
Nico

Reputation: 3542

you are clearing your list via row.Clear(). You should create a new row with row = new List<char>()

public void loadPatterns()
{
    string[] files = Directory.GetFiles("patterns/");
    Level pattern = new Level();
    List<char> row = new List<char>();
    List<List<char>> grid = new List<List<char>>();

    for(int i = 0; i < files.Length; i++)
    {
        var lines = File.ReadLines(files[i]);
        foreach(string line in lines)
        {
            foreach(char c in line)
            {
                row.Add(c);
            }
            grid.Add(row);
            row = new List<char>(); // <-
        }
        pattern.grid = grid;
        patterns.Add(pattern);
        grid.Clear();
    }
}

Upvotes: 3

Related Questions