The accepted answer is absoluelty right regarding how it works. But I think not allowing a programmer to make that change is a bit of an overreach.
There may very well be a good reason to want to do this.
Here is mine:
class MYClass
{
private List<OffsetParameters> offsetList = new List<OffsetParameters>();
internal List<OffsetParameters> OffsetParamList
{
get { return this.offsetList; }
}
where OffsetParameters is a struct (value type)
internal struct OffsetParameters
{
...
All is well - the list does not have a setter and the contents of it are of value type so they are protected from the consumer.
So now I want to add a method to MyClass to update something in that struct. Here is my first thought
instantiate a new list, do a foreach on the old list where I update the iteration var which is already copy. Add that copy to the new list.
Assign offsetList the new list after the for each.
internal void UpdateColors(Dictionary<string, string> nameColorMap)
{
if (nameColorMap == null)
return;
List<OffsetParameters> newOffsetParamList = new List<OffsetParameters>();
foreach (OffsetParameters param in offsetList)
{
if (nameColorMap.ContainsKey(param.offsetName))
param.color = nameColorMap[param.offsetName];
newOffsetParamList.Add(param);
}
offsetList = newOffsetParamList;
}
Seems legit, but because of this restriction I have to make yet another copy of that copy (inefficient).
I know this does not answer the question, but it does not fit in a comment to the official answer and it adds smthng important to the picture.
My solution was to use indexer on that list instead of an enumerator just an FYI in case you are in the same boat:
internal void ChangeOffsetGroupColors(Dictionary<string, string> nameColorMap)
{
if (nameColorMap == null)
return;
List<OffsetParameters> newOffsetParamList = new List<OffsetParameters>();
for (int i = 0; i < offsetList.Count; i++)
{
OffsetParameters param = offsetList[i];
if (nameColorMap.ContainsKey(offsetList[i].offsetName))
param.color = nameColorMap[offsetList[i].offsetName];
newOffsetParamList.Add(param);
}
offsetList = newOffsetParamList;
}
I bet you List.Count gets recalculated every loop iteration :) watch out for that if you want efficiency
foreach
loop variable could not be modified, but I never really learned why! – Katushka