#327 – Assigning a struct to a New Variable Makes a Copy

Because a struct is a value type, you make a copy of the entire struct when you assign it to a new variable.

Assume that we define the following struct:

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

If we define a variable of this type and then assign it to another variable, the second variable gets a copy of all of the data. If we then change some field in the first copy, the second copy is unchanged.

            MovieInfo goneWithWind;
            goneWithWind.Title = "Gone With the Wind";
            goneWithWind.Year = 1938;
            goneWithWind.Director = "Victor Fleming";

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

            // Fix the year
            goneWithWind.Year = 1939;

            Console.WriteLine(goodClarkGableFlick.Year);    // Oops, still 1938
Advertisements