#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

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

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

  1. Pingback: #328 – Copying a struct Will Not Copy Underlying Reference Types « 2,000 Things You Should Know About C#

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: