0

I have a readonly List that contains a few coordinates.

private readonly List<float[]> rightPositions = new List<float[]>()
{
    new float[2] { 250, 0 },
    new float[2] { 350, -200 },
    new float[2] { 350, 200 },
    new float[2] { 600, 0 }
};

In the following method I give the static data from List<float[]> rightPositions to the field rTeam.PlayerArray[iterator].Position.

private void ClearPlayers(Team rTeam, Team lTeam)
    {
        for (int iterator = 0; iterator < rTeam.PlayerArray.Length; iterator++)
        {
            rTeam.PlayerArray[iterator].Position = rightPositions.ElementAt(iterator);
        }  
    }

The first time ClearPlayers(Team rTeam, Team lTeam) is executed, the data from the List<float[]> rightPositions is put in the rTeam.PlayerArray[iterator].Position. After the first time, the data in the readonly List<float[]> rightPositions is not the same as before.

Did I miss something obvious? Or do I need to use something els than a readonly field?

Thanks in advance.

  • @poke In this case it's not a complete duplicate. Even if the *list* were immutable the objects *inside* it aren't and that's what was the problem here. – Sami Kuhmonen May 20 '17 at 12:32

2 Answers2

0

The readonly only means "you cannot change the value of this variable." You can change whatever is inside the list but you cannot create a new list.

It also doesn't change how the actual contents work. You create float arrays, assign them somewhere and they are still pointing to the same array so any changes you make to them will affect the arrays in this list.

You will have to clone the arrays if you want to keep them from changing.

rTeam.PlayerArray[iterator].Position = (float[])rightPositions.ElementAt(iterator).Clone();

Another way would be to use structs since I assume Position has X and Y coordinates so it would be more logical to have a struct with X and Y and then assigning would copy the data and not change it in any way in the source. It would also most likely make the code clearer.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74
0

The List is not read-only. A List can't be read-only. It's the property that's read-only. That means that you can't assign a different List object to that property but once you get the List object from the property, it is just like any other List, so you can modify it as you like. If you want the collection to be read-only then use a ReadOnlyCollection rather than a List.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46