skip to content

In C#, `string` is a reference type, so why does a method that appends to its `string` parameter leave the caller's string unchanged?

level: juniorimportance: must knowfreq 75%

answer

  1. no member changes a string
  2. += builds a new object
  3. parameter holds a copied reference
  4. rebinding vs mutating

basics

~20 s

Strings are immutable: s += x builds a new string and stores it in the method's own parameter, which is a copy of the caller's reference. The caller's variable still refers to the original string, which nothing can change.

solid answer

~40 s

A `string` parameter holds a copy of the caller's **reference**, exactly like any class parameter. The difference is that `string` has no member that changes its characters: the indexer `string.this[int]` has only a getter, and `ToUpper`, `Replace`, `Trim` and `+` all return new strings. So `s += " [new]"` creates a new string and rebinds the parameter; the caller's variable still points at the untouched original. Compare a `List<string>` parameter: `t.Add("sale")` mutates the shared list, so the caller sees it, while `t = new List<string>()` only rebinds the parameter. To hand a new string back, return it, or pass the variable with `ref`, which belongs with method parameters.

code

csharp · 21 lines
csharp
string label = "Kettle";
string shown = label;               // both variables refer to one string object
AddBadge(label);
label += " (sale)";                 // builds a new string, rebinds only 'label'
Console.WriteLine($"label = {label}");
Console.WriteLine($"shown = {shown}");

var tags = new List<string> { "kitchen" };
Tag(tags);
Console.WriteLine($"tags = {string.Join(", ", tags)}");

static void AddBadge(string s)
{
    s += " [new]";                  // new string; the caller's variable is untouched
}

static void Tag(List<string> t)
{
    t.Add("sale");                  // mutates the shared list: the caller sees it
    t = new List<string> { "lost" }; // rebinds the parameter copy only
}

go deeper

for a junior

Recall that string is a reference type with no way to change its contents, so every apparent edit creates a new string.

for a middle

Explain the difference between rebinding a parameter and mutating the object it refers to, using string and List<string> side by side.

for a senior

Spot discarded results such as a bare ToUpper call and helpers that rebind a parameter, and fix them by returning the new value.

for a principal

Use string as the model for when an immutable reference type is the right design for widely shared values.

## Two facts that look like they conflict C# `string` (an alias for `System.String`) is a **reference type**: a `string` variable holds a reference to a `System.String` object, and assigning one string variable to another copies that reference. Yet strings behave as if each variable owned its own text. Two facts reconcile this: - **Strings are immutable.** Once a `string` object exists, no operation changes its characters. Microsoft's reference for the type says so directly: code that appears to modify a string creates a new string object instead. - **Rebinding is not mutating.** Assigning a new string to a variable changes which object that one variable refers to; it does nothing to the object the variable used to refer to, or to any other variable. ## What a string parameter receives On the inventory screen, a helper decorates a product label: ```csharp static void AddBadge(string s) { s += " [new]"; } ``` The call `AddBadge(label)` copies the caller's reference into `s`, so for a moment both point at the same `"Kettle"` object. Then: 1. `s + " [new]"` allocates a **new** string `"Kettle [new]"`; 2. the assignment stores that new reference in `s`, the method's own variable; 3. the method returns and `s` disappears; `label` still refers to `"Kettle"`. Nothing could have changed the original object, because `string` offers no way to do it. ## Strings vs a mutable reference type The same copying of references produces visible changes for a mutable class, which is why the comparison is the core of the interview answer: | Operation on the parameter | `string s` | `List<string> t` | |---|---|---| | copy the caller's reference in | yes | yes | | change the shared object | impossible | `t.Add("sale")` - caller sees it | | rebind the parameter | `s += "x"` - caller does not see it | `t = new List<string>()` - caller does not see it | The rebinding row behaves identically for both types. Only the middle row differs, and it differs because `List<T>` has mutating members and `string` does not. ## Where immutability shows up in everyday code - **The indexer is read-only.** `s[0] = 'K';` fails with CS0200, "Property or indexer 'string.this[int]' cannot be assigned to -- it is read only". - **Methods return results.** `sku.ToUpper();` on its own line compiles and does nothing useful; the upper-case string is created and discarded. The fix is `sku = sku.ToUpper();`. - **`+=` in a loop** builds a new string on every pass; the cost and `StringBuilder` belong to the lesson on string building. - **Sharing is safe.** Because no holder can change a string, handing the same reference to many screens, caches or threads never lets one of them alter what the others see. String `==` comparing text rather than references is a separate overload, covered with equality. ## Reading the code: rebinding or mutating? When a reviewer has to predict whether a change reaches the caller, three questions settle it for any reference type, string included: 1. **Does the statement assign to the variable itself?** `s = ...`, `s += ...` and `t = new List<string>()` change which object that one variable refers to. Every other variable, including the caller's argument, keeps its old reference. 2. **Does the statement change the object through a member?** `t.Add(...)` or `product.Price = 0m` changes the shared object, so every holder of the reference sees it. For `string` this case cannot occur, because the type exposes no mutating member. 3. **Is the variable a parameter without `ref`?** Then it is the method's own copy of the caller's reference, so case 1 never reaches the caller and only case 2 can. Applied to `AddBadge`, the statement is case 1 on a plain parameter, so the caller's label cannot change, whatever the method appends. ## How to give the caller a new string - **Return it**, `static string AddBadge(string s) => s + " [new]";`, and assign the result at the call site. This is the idiomatic C# shape. - **Pass the variable by reference** with `ref string s`, so the method rebinds the caller's own variable; parameter modifiers are covered with method parameters. - **Use a mutable holder** such as `StringBuilder` when many edits happen in one place. A strong answer states both facts in one breath: the parameter receives a copied reference, and a string's content can never change, so `+=` can only rebind the method's own variable.

  • Why does `sku.ToUpper();` on its own line leave `sku` unchanged?
    `ToUpper` cannot change the string it is called on, because strings are immutable. It returns a new upper-case string, and a statement that ignores the return value throws that string away. The fix is `sku = sku.ToUpper();`.
  • How would you let `AddBadge` hand a decorated label back to its caller?
    Return the new string, `static string AddBadge(string s) => s + " [new]";`, and assign it at the call site with `label = AddBadge(label);`. Passing the variable with `ref` would also work, but returning a value is the idiomatic shape for strings.

  • string is a value type in C#, which is why it seems copied.
  • s += x appends to the existing string object in place.
  • Calling sku.ToUpper() converts sku to upper case.
  • Passing a string to a method copies all of its characters.
  • Reassigning a reference-type parameter also changes the caller's variable.