# [.net] C# Generic List Iteration

This topic is 4994 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

When I try to edit values in a list, by looping through it like the code below, I get the error "Cannot modify members of 'list' because it is a 'foreach iteration variable'".
foreach (Item item in my_list)
{
item.var = 3;
}
I also tried doing this with a for loop like this, and get the error "Cannot modify the return value of 'System.Collections.Generic.List<list>.this[int]' because it is not a variable"
for (int i = 0; i < my_list.Count; i++)
{
my_list.var = 3;
}
So how can you change the contents of a list in this way? Is the only way to add an entire new item to the list and remove the old item?

##### Share on other sites
It sounds like the type of my_list is a class you've defined called 'list'. Can you show us the definition of the type of my_list?

##### Share on other sites
Is item a struct? I played around with this and found that it did fine with classes (properties or variables) but failed with structs. Probably fails because structs are a value type and the iteration element is a copy of what is actually in the list. Even if you could change it, your change would be lost.

This will probably work in the body of your second loop.

Item item = my_list; //make a copy
item.var = 3;
my_list = item; //reassign the entire value

For your first loop you are out of luck unless you switch to a reference type.

##### Share on other sites
Yes its a problem with it being a struct. Simply changing it to a class solved the problem. Thanks. [cool]

1. 1
2. 2
Rutin
22
3. 3
JoeJ
18
4. 4
5. 5

• 15
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631724
• Total Posts
3001903
×