In C#, a method meant to replace the caller's List<string> assigns a new list to its parameter, but the caller keeps the old list; why?
answer
- two variables, one object
- copy of the reference
- mutate versus rebind
- ref aliases the variable itself
basics
~20 sA List<string> parameter holds a copy of the caller's reference. Calling Add through it changes the shared list, but assigning a new list rebinds only the method's copy. Declare the parameter ref, or return the new list.
solid answer
~40 sC# passes arguments by value unless the parameter says otherwise, and for a class type the value is the *reference*. Inside the method, `list` and the caller's `shapes` are two variables pointing at one object: `list.Add(...)` mutates that object, so the caller sees it, but `list = new List<string>()` only makes the method's own variable point elsewhere. To replace the caller's list, declare `ref List<string> list` and call it with `ref shapes`, or, usually cleaner, return the new list and let the caller assign it. Clearing and refilling the existing list also works, but then every other holder of that list sees the change too.
code
csharp · 19 linesvar shapes = new List<string> { "circle" };
Shapes.ReplaceByValue(shapes);
Console.WriteLine($"after by-value replace: {string.Join(", ", shapes)}");
Shapes.MutateByValue(shapes);
Console.WriteLine($"after by-value mutate: {string.Join(", ", shapes)}");
var alias = shapes;
Shapes.ReplaceByRef(ref shapes);
Console.WriteLine($"after by-ref replace: {string.Join(", ", shapes)}");
Console.WriteLine($"old alias still sees: {string.Join(", ", alias)}");
static class Shapes
{
public static void ReplaceByValue(List<string> list) => list = ["square"]; // rebinds the copy only
public static void MutateByValue(List<string> list) => list.Add("triangle"); // same object as the caller's
public static void ReplaceByRef(ref List<string> list) => list = ["hexagon"]; // rebinds the caller's variable
}go deeper
Recall that a class argument is a copy of the reference: changes to the object are shared, assigning the parameter is not.
Explain mutating versus rebinding with a small table of operations, and what ref adds for a reference-type parameter and what it leaves untouched, such as other aliases.
Spot the silent no-op initialiser in review and choose between returning a value, ref, and in-place mutation based on who else holds the list.
Set a convention: methods that produce a new collection return it, and ref on a class-typed parameter needs a stated reason in the API's documentation.
## Two variables, one object A **reference type** such as `List<string>` lives on the managed heap, and a variable of that type holds a **reference** to it, not the list itself. C# passes arguments **by value** by default, which for a class means the method receives a *copy of the reference*. After the call starts there are two variables, the caller's `shapes` and the method's `list`, and both refer to the same `List<string>` object. This is the source of a common mix-up. "Objects are passed by reference" is a loose way of saying that the *object* is shared; the *variable* is not. Anything done to the object through either variable is visible through the other. Anything done to one variable, such as making it refer to a different object, is invisible to the other. ## Mutating versus rebinding | Inside the method | `List<string> list` (by value) | `ref List<string> list` | |---|---|---| | `list.Add("triangle")` | caller sees the new item | caller sees the new item | | `list.Clear()` | caller's list is emptied | caller's list is emptied | | `list = new List<string>()` | caller unaffected | caller's variable now refers to the new list | | `list = null` | caller unaffected | caller's variable becomes null | The first two rows are **mutation**: they go through the reference to the shared object, so passing by value or by reference makes no difference. The last two rows are **rebinding**: they change which object a variable refers to, and only a by-reference parameter can rebind the caller's variable. The C# documentation puts it the same way: reassigning a parameter passed by value is never visible to the caller, whether the type is a value type or a reference type. ## What ref changes, and what it does not With `ref`, the parameter is an alias for the caller's *variable*, so `list = ["hexagon"]` writes a new reference into `shapes` itself. The rebinding is precise, though: it changes that one variable. Any other variable or field that held the old reference, say `var alias = shapes;` taken before the call, still points at the original list, and the original list is untouched. `ref` does not copy the list and does not track every reference to it. Passing a class instance by `ref` also changes nothing about member access. A method that only calls `Add`, `Remove` or property setters behaves identically with or without `ref`, so on a class-typed parameter the modifier tells a reviewer one specific thing: this method may make the caller's variable refer to a different object. ## Three ways to replace a list 1. **Return it.** `static List<string> Rebuild(List<string> old)` and `shapes = Rebuild(shapes);`. The data flow is visible at the call site, the target can be a property (`order.Lines = Rebuild(order.Lines)`), and the method stays usable from `async` code. 2. **Take it by `ref`.** `static void Rebuild(ref List<string> list)` and `Rebuild(ref shapes);`. Useful when the method decides whether to replace at all, but the caller must own an assignable variable: a property cannot be passed by `ref`. 3. **Mutate in place.** `list.Clear(); list.AddRange(newItems);`. No new object, so every holder of the list sees the new contents. That is right when the list is shared state everyone should see, and a surprise when some caller kept the old contents on purpose. ## Where this shows up in code review - An initialiser such as `void Load(List<Item> items) { items = repository.GetAll(); }` compiles without a warning and silently does nothing for the caller. - A cleanup method such as `void Release(Connection connection) { connection = null; }` leaves the caller's variable pointing at the object. - A `void` method whose purpose is to produce a new object is the smell to look for: its result can only escape by mutation, a `ref` or `out` parameter, or a field, and returning it is usually the clearest of these. - A `string` parameter can only ever be rebound, since strings are immutable, so the same rule explains why appending to a string parameter never reaches the caller; that case belongs with the lesson on value and reference semantics. - A `struct` parameter is a full copy, so for a struct even assigning its fields stays local unless the parameter is `ref`; the struct lessons cover that side.
- Does passing a class instance by ref change anything if the method only calls its members?No observable difference. Member calls go through the same object either way; `ref` only adds the ability to make the caller's variable refer to a different object or to null. That is why `ref` on a class-typed parameter tells a reviewer the method may rebind the caller's variable.
- Why is returning the new list usually better than a ref parameter?A return value makes the data flow visible at the call site (`shapes = Rebuild(shapes)`), lets the target be a property, and keeps the method usable in `async` methods and iterators, which reject by-reference parameters. `ref` requires the caller to own an assignable variable and hides the rebinding inside the call.
- Objects are passed by reference in C#, so assigning the parameter replaces the caller's object.
- Passing a List<T> to a method copies the list, so Add inside the method is not seen.
- A class parameter needs ref for the method to change the object's contents.
- After a ref reassignment, every variable that held the old list sees the new one.