Not able to modify object of struct in loop

c#, collections

Solution

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:

public class Foo {
    public string Bar {get;set;}
}

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:

public struct Foo {
    private readonly string bar;
    public string Bar { get {return bar; }}
    public Foo(string bar) {this.bar = bar;}
}

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 use `foreach`), but correct.

But IMO, use a class. Structs are pretty rare, to be honest. If you aren't sure: class.

Problem

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

Original source