#777 – A struct Isn’t Mutable When Used as a Property

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();

777-001

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();

777-002

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #777 – A struct Isn’t Mutable When Used as a Property

  1. Pingback: Dew Drop – February 12, 2013 (#1,497) | 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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: