#779 – Methods in struct that Modify Elements Can Be Dangerous
February 13, 2013 1 Comment
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.
// Method that modifies struct works if local DogCollarInfo collar = new DogCollarInfo(0.5, 8.0); collar.Dump(); collar.DoubleLength(); collar.Dump();
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.
// Does not work if struct is property Dog d = new Dog("Kirby"); d.Collar = new DogCollarInfo(0.5, 8.0); d.Collar.Dump(); d.Collar.DoubleLength(); d.Collar.Dump(); // Length not doubled!