#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[1].Length = 22.0; // Do this instead collarList[1] = new DogCollarInfo(collarList[1].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[2]; arr[0] = new DogCollarInfo(0.5, 14.0); arr[0].Length = 5.0; // OK
Hi Sean,
Referencing the item by indexing into an array does not return a copy of the struct ?
No. You can use an array indexer to change struct members directly.
List can’t but array can. What is the reason ??
It’s just a design decision.
I got it. Thanks for your answer. Look forward to reading more of your articles about Design Pattern =)