Sign in to follow this  

[.net] C# Generic List Iteration

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

If you intended to correct an error in the post then please contact us.

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[i].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 this post


Link to post
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[i]; //make a copy
item.var = 3;
my_list[i] = item; //reassign the entire value

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

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this