#328 – Copying a struct Will Not Copy Underlying Reference Types

Assigning a struct to a new variable will make a copy of the contents of the struct.  After the assignment, two copies of the struct will exist, which can be changed independently.

If the struct contains any reference-typed fields, only a reference to an object is copied.  Both copies of the struct will then refer to the same object.

Assume that we define the following struct:

        public struct MovieInfo
        {
            public string Title;
            public int Year;
            public Person Director;
        }

If we make a copy of the MovieInfo struct through an assignment, the Director field in the two copies will point to the same Person object.

            MovieInfo goneWithWind;
            goneWithWind.Title = "Gone With the Wind";
            goneWithWind.Year = 1939;
            goneWithWind.Director = new Person("Victor", "Fleming");

            // Actually makes a copy of entire struct
            MovieInfo goodClarkGableFlick = goneWithWind;

            // Change director's name
            goneWithWind.Director.FirstName = "Victoria";

            Console.WriteLine(goneWithWind.Director);            // Victoria Fleming
            Console.WriteLine(goodClarkGableFlick.Director);     // Victoria Fleming
Advertisements

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

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 )

w

Connecting to %s

%d bloggers like this: