[.net] C# Generic List Iteration

Started by
2 comments, last by Rebooted 19 years, 5 months ago
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?
Advertisement
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?
- k2"Choose a job you love, and you'll never have to work a day in your life." — Confucius"Logic will get you from A to B. Imagination will get you everywhere." — Albert Einstein"Money is the most egalitarian force in society. It confers power on whoever holds it." — Roger Starr{General Programming Forum FAQ} | {Blog/Journal} | {[email=kkaitan at gmail dot com]e-mail me[/email]} | {excellent webhosting}
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.
Yes its a problem with it being a struct. Simply changing it to a class solved the problem. Thanks. [cool]

This topic is closed to new replies.

Advertisement