var names = new[] {
new { Name = "John", Age = 44 },
new { Name = "Diana", Age = 45 },
new { Name = "James", Age = 17 },
new { Name = "Francesca", Age = 15}
};
for (int i = 0; i < names.Length; i++)
{
names[i].Age = 23; //-------->Error
names[i] = new { Name = "XYX", Age = 26 }; //----->Works fine
}
foreach(var name in names)
{
name.Age = 1; //-------->Error
name = new { Name = "ABC", Age = 25 }; //-------->Error
}
I have two questions here.
1. Why I was not able to change the any attribute of an iteration variable.
2. I was only able to assign a new object to the iteration variable in for loop. Not in foreach loop. Why?
Question 1: Why I was not able to change the any attribute of an iteration variable?
From the documentation on Anonymous Types:
You cannot change the values of the properties in your anonymous type, so
are equally invalid.
Question 2. I was only able to assign a new object to the iteration variable in for loop. Not in foreach loop. Why?
From the documentation on IEnumerable:
You would invalidate the iterator if you change the backing list in any way. Consider what would happen if the iterator returned the items in a specific order based on the Age field, for example.