Jump to content
  • Advertisement
Sign in to follow this  
Rebooted

[.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.

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.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
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?

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; //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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!