#328 – Copying a struct Will Not Copy Underlying Reference Types
May 19, 2011 Leave a comment
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