#777 – A struct Isn’t Mutable When Used as a Property
February 11, 2013 1 Comment
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.
// Create struct
DogCollarInfo collar1 = new DogCollarInfo(0.5, 14.0);
collar1.Dump();
// Modify data in struct
collar1.Length = 20.0;
collar1.Dump();
However, if a struct is used as a property in another object, we can’t modify its members.
// 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:
// Do this instead
d.Collar = new DogCollarInfo(d.Collar.Width, 10.0);
Console.WriteLine("Dog's collar:");
d.Collar.Dump();


Pingback: Dew Drop – February 12, 2013 (#1,497) | Alvin Ashcraft's Morning Dew