In C#, what happens when you assign a struct variable to another variable and change the copy, versus doing that with a class instance?
answer
- what the variable itself holds
- value copied vs reference copied
- same rule for arguments and returns
- reference fields inside a struct
basics
~20 sAssigning a struct copies the whole value, so changing the new variable leaves the original untouched. Assigning a class instance copies only the reference, so both variables reach one object and an edit through either shows through both.
solid answer
~40 sA struct variable holds the value itself, so `var moved = shelf;` copies every field and `moved.X = 10` leaves `shelf.X` alone. A class variable holds a reference, so `var shown = product;` copies the reference and `shown.Price = 25m` changes the one `Product` both names reach; `ReferenceEquals(product, shown)` is `true`. The same rule applies when you pass an argument or return a result: a struct parameter is a separate copy, a class parameter is a second reference to the caller's object. The copy is shallow: a struct with a `List<string>` field copies the list reference, so both copies share that list.
code
csharp · 23 linesvar shelf = new Point(1, 2);
var moved = shelf; // struct: the whole value is copied
moved.X = 10;
Console.WriteLine($"shelf.X = {shelf.X}, moved.X = {moved.X}");
var product = new Product { Name = "Kettle", Price = 30m };
var onScreenB = product; // class: only the reference is copied
onScreenB.Price = 25m;
Console.WriteLine($"product.Price = {product.Price}, onScreenB.Price = {onScreenB.Price}");
Console.WriteLine(ReferenceEquals(product, onScreenB));
struct Point
{
public int X;
public int Y;
public Point(int x, int y) { X = x; Y = y; }
}
class Product
{
public string Name = "";
public decimal Price;
}go deeper
Recall the one rule: assignment copies what the variable holds, a whole value for a struct and a reference for a class. Predict the printed values from that.
Explain that arguments and return values follow the same copy rule, and that struct copies are shallow, so reference-type fields stay shared between copies.
Show how this rule explains real bugs: an edit lost on a struct copy, or one object edit surfacing on every screen that holds the same reference.
Frame the choice of struct or class as a choice of identity: whether callers should share one mutable thing or each own an independent value.
## What a C# variable holds C# divides types into **value types** (every `struct`, the numeric types, `bool`, `char`, enums, value tuples) and **reference types** (every `class`, `string`, arrays, delegates, interfaces). The difference is what a variable of the type contains: - a **value-type variable** contains the instance itself, every field of it; - a **reference-type variable** contains a **reference**, a pointer-like handle to an object that lives elsewhere. C# then applies one rule everywhere: **assignment, passing an argument and returning a result copy the variable's contents**. Microsoft's language reference states it the same way. Because the two kinds of variable hold different things, the one rule produces two different behaviours. ## Struct assignment copies the value Take an inventory screen that stores a shelf position as a `Point` struct with public `X` and `Y` fields: ```csharp var shelf = new Point(1, 2); var moved = shelf; // copies X and Y moved.X = 10; // shelf.X is still 1 ``` After the assignment there are two independent `Point` values. Changing `moved` cannot affect `shelf`, because nothing connects them. This is called **value semantics**: the variable *is* the data. ## Class assignment copies the reference The same screen models a product as a `Product` class: ```csharp var product = new Product { Name = "Kettle", Price = 30m }; var shown = product; // copies the reference only shown.Price = 25m; // product.Price is now 25 ``` There is still exactly one `Product` object. `product` and `shown` are two references to it, so `ReferenceEquals(product, shown)` returns `true` and a price edit made by one screen shows up on every screen that holds the same reference. This is **reference semantics**: the variable *points at* the data. | Step | `Point` (struct) | `Product` (class) | |---|---|---| | `var b = a;` | copies every field | copies one reference | | `b.X = 10` / `b.Price = 25m` | changes `b` only | changes the shared object | | `ReferenceEquals(a, b)` | not meaningful for values | `true` | | passing to a method | the method gets a copy | the method gets a second reference | ## The same rule for arguments and return values A method parameter is a new variable initialised from the argument, so it follows the assignment rule: 1. A method that sets `p.X = 0` on a `Point` parameter changes its own copy; the caller's `Point` is unchanged. 2. A method that sets `p.Price = 0m` on a `Product` parameter changes the caller's object, because the parameter is a second reference to it. 3. A method that *reassigns* a `Product` parameter, `p = new Product();`, rebinds only its own reference; the caller still holds the original object. The `ref`, `out` and `in` modifiers, which pass the caller's variable itself instead of a copy, are covered with method parameters. ## Shallow copies: a struct that holds a reference Copying a struct copies its fields **as they are**. A field of a reference type is copied as a reference, not cloned: - a `Point` copy is fully independent, because `int` fields are values; - a struct with a `List<string> Tags` field yields two structs whose `Tags` fields point at **one** list, so `copy.Tags.Add("x")` is visible through the original; - reassigning `copy.Tags = new List<string>()` breaks the link for the copy only. This is why a struct is only as independent as its fields: a value type that wraps mutable reference-type state shares that state across every copy. ## How interviewers probe it - They show the four-line snippet and ask for the printed value; the answer turns on whether the type is a `struct` or a `class`, not on the variable names. - They ask whether `new` on a struct allocates an object; it initialises a value in the variable's storage, it does not create a shared instance. - They ask what `MemberwiseClone` has to do with assignment: nothing, since plain assignment never clones an object. The practical consequence on the inventory screen is the pair of bugs in its scenario: a `Point` edited through a copy "does nothing", while one `Product` edit appears everywhere. Both are the same rule applied to two kinds of variable.
- A struct has a `List<string> Tags` field. You copy the struct and call `copy.Tags.Add("x")`. What does the original see?It sees the new item. Copying a struct copies each field as it is, and a `List<string>` field holds a reference, so both structs point at one list. Only assigning a new list to `copy.Tags` would separate them, and that affects the copy alone.
- A method sets `p.X = 0` on a `Point` parameter and `q.Price = 0m` on a `Product` parameter. Which change does the caller see?Only the price change. The `Point` parameter is a copy of the caller's value, so setting `X` changes the method's copy. The `Product` parameter is a second reference to the caller's object, so setting `Price` changes that object. Passing the caller's variable itself needs `ref`, which belongs with method parameters.
A struct assignment is handing someone a photocopy of a form; a class assignment is handing them the link to a shared online form. If the photocopied form carries a link written on it, both copies still lead to the same shared page.
- Assigning a class instance to a new variable creates a copy of the object.
- A struct assignment copies a reference, just like a class assignment.
- Copying a struct also clones every object its fields reference.
- Using new on a struct creates a shared heap object like a class.
- Plain assignment calls MemberwiseClone behind the scenes.