Methods in struct that Modify Elements Can Be Dangerous

If you have a method in a struct that modifies a data member of the struct, you can run into unexpected results, due to the value type semantics of the struct.
Assume that we have a struct that includes a method that can change the value of one of its data members.  The method works just fine for a locally defined instance of the struct.
1
2
3
4
5
// Method that modifies struct works if local
DogCollarInfo collar = new DogCollarInfo(0.5, 8.0);
<span class="skimlinks-unlinked">collar.Dump</span>();
collar.DoubleLength();
<span class="skimlinks-unlinked">collar.Dump</span>();
779-001
But if you have a property of some class whose type is this struct, it’s no longer safe to call this method. Because the property’s get accessor returns a copy of the struct, the data in the original struct won’t get modified.
1
2
3
4
5
6
// Does not work if struct is property
Dog d = new Dog("Kirby");
d.Collar = new DogCollarInfo(0.5, 8.0);
<span class="skimlinks-unlinked">d.Collar.Dump</span>();
d.Collar.DoubleLength();
<span class="skimlinks-unlinked">d.Collar.Dump</span>();   // Length not doubled!


779-002