#779 – 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.

            // Method that modifies struct works if local
            DogCollarInfo collar = new DogCollarInfo(0.5, 8.0);
            collar.Dump();
            collar.DoubleLength();
            collar.Dump();

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.

            // 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!

779-002

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #779 – Methods in struct that Modify Elements Can Be Dangerous

  1. Pingback: Dew Drop – February 13, 2013 (#1,498) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: