A struct Isn’t Mutable When Used as a Property

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 struct
DogCollarInfo collar1 = new DogCollarInfo(0.5, 14.0);
collar1.Dump();
 
// Modify data in struct
collar1.Length = 20.0;
collar1.Dump();
777-001
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 property
Dog d = new Dog("Kirby");
d.Collar = collar1;
 
// Compile-time error: Can't modify Collar because it's not a variable
d.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 instead
d.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>();


777-002