I have a List of structure.In the loop i am trying to modify the object’s property,which is happening,but when i (Quick look in Visual studio)look into the list object ,the new value is not reflecting.Is it by virtue that the structure’s object cannot be modified when in a collection?
I am using generics list with the struct as the type in the list
I have a List of structure.In the loop i am trying to modify the
Share
You mention “modify the object’s property” in the context of a struct, but importantly a struct is not an object. Other people have answered as to the issue with structs being copied (and changes discarded), but to take that further the real problem here is that you have a mutable (changeable) struct at all. Unless you are on XNA (or similar) there is simply no need.
If you want to be able to change properties, make it a class:
This is now a reference-type, and your changes (
obj.Bar = "abc";) will be preserved through the foreach. If you really want/need a struct, make it immutable:Now you can’t make the mistake of changing the value of a copy; you would instead have to use the indexer to swap the value (
list[i] = new Foo("abc");). More verbose (and you can’t useforeach), but correct.But IMO, use a class. Structs are pretty rare, to be honest. If you aren’t sure: class.