#778 – A struct Isn’t Mutable When Used in a Collection
February 12, 2013 5 Comments
A struct is normally mutable, i.e. you can modify the values of its members directly.
However, if a struct is used in a collection class, like a List<T>, you can’t modify its members. Referencing the item by indexing into the collection returns a copy of the struct, which you can’t modify. To change an item in the list, you need to create a new instance of the struct.
List<DogCollarInfo> collarList = new List<DogCollarInfo>(); // Create a few instances of struct and add to list collarList.Add(new DogCollarInfo(0.5, 14.0)); collarList.Add(new DogCollarInfo(0.3, 12.0)); // Compile-time error: Can't modify '...' because it's not a variable collarList.Length = 22.0; // Do this instead collarList = new DogCollarInfo(collarList.Width, 22.0);
If you store the structs in an array, then you can change the value of one of the struct’s members.
DogCollarInfo arr = new DogCollarInfo; arr = new DogCollarInfo(0.5, 14.0); arr.Length = 5.0; // OK