A struct is normally mutable, i.e. you can modify the values of its members directly. Assume that we have a DogCollarInfo struct with Width and Length members. We can create the struct and then later modify it.
1 2 3 4 5 6 7 | // Create structDogCollarInfo collar1 = new DogCollarInfo(0.5, 14.0);collar1.Dump();// Modify data in structcollar1.Length = 20.0;collar1.Dump(); |
However, if a struct is used as a property in another object, we can’t modify its members.
1 2 3 4 5 6 | // Create Dog object and set Collar propertyDog d = new Dog("Kirby");d.Collar = collar1;// Compile-time error: Can't modify Collar because it's not a variabled.Collar.Length = 10.0; |
Because the struct is a value type, the property accessor (get) returns a copy of the struct. It wouldn’t make sense to change the copy, so the compiler warns us.
You can instead create a new copy of the struct:
1 2 3 4 | // Do this insteadd.Collar = new DogCollarInfo(<span class="skimlinks-unlinked">d.Collar.Width</span>, 10.0);Console.WriteLine("Dog's collar:");<span class="skimlinks-unlinked">d.Collar.Dump</span>(); |

