skip to content

Text and Characters

string is immutable UTF-16 text: concatenation, interpolation, raw literals, comparison rules and Unicode all have traps. Interviewers ask about StringBuilder and culture bugs.

on this pageshow

explore

questions

21

In C#, why does building a 200,000-line CSV export with `csv += line` in a loop allocate so much, and how does StringBuilder fix it?

level: juniorimportance: must knowfreq 80%

answer

  1. strings never change in place
  2. += becomes a Concat call
  3. each pass recopies everything so far
  4. one growable buffer, one final copy

basics

~20 s

A .NET string cannot change after creation, so csv += line compiles to csv = string.Concat(csv, line), allocating a new string and recopying all earlier text on every pass. StringBuilder appends into a growable buffer and copies once, in ToString().

solid answer

~40 s

`string` is immutable: no member changes an existing instance, and methods such as `Trim` or `Replace` return a new string. So `csv += line` is compiled to `csv = string.Concat(csv, line)`, which allocates a string as long as both parts and copies the old text into it. Over n lines that recopies roughly n²/2 lines' worth of characters: in a test with 20,000 short lines the loop allocated about 8.4 GB to produce a 427,000-character result, and once the partial string reaches 85,000 bytes every new copy goes to the large object heap. `StringBuilder` keeps a mutable character buffer instead: `Append` copies only the new characters, growth adds a chunk without moving the old text, and `ToString()` copies everything once into the final string. The same test with a `StringBuilder` allocated about 3 MB.

code

csharp · 21 lines
csharp
using System.Text;

const int Rows = 20_000;
string Line(int i) => $"{i},SKU-{i % 977},3,19.99\n";

long before = GC.GetAllocatedBytesForCurrentThread();
string csv = "";
for (int i = 0; i < Rows; i++)
    csv += Line(i);                       // csv = string.Concat(csv, Line(i))
long concatBytes = GC.GetAllocatedBytesForCurrentThread() - before;

before = GC.GetAllocatedBytesForCurrentThread();
var sb = new StringBuilder();
for (int i = 0; i < Rows; i++)
    sb.Append(Line(i));                   // copies only the new line's characters
string csv2 = sb.ToString();              // one final copy into a new string
long builderBytes = GC.GetAllocatedBytesForCurrentThread() - before;

Console.WriteLine($"length: {csv.Length} == {csv2.Length}");
Console.WriteLine($"+= loop:       {concatBytes / 1_000_000} MB allocated");
Console.WriteLine($"StringBuilder: {builderBytes / 1_000_000} MB allocated");

go deeper

for a junior

Say that strings are immutable, that += creates a new string each time, and that StringBuilder is the tool for building text in a loop. Show the Append-then-ToString shape.

for a middle

Explain that += lowers to string.Concat(string, string), why the copying grows quadratically, and how Append copies only new characters while ToString copies once.

for a senior

Bring numbers and side effects: allocation measured with GetAllocatedBytesForCurrentThread, large intermediate strings landing on the large object heap, and when to stream output instead of building one giant string.

for a principal

Frame it as a review rule: StringBuilder or string.Join when the part count depends on data, plain + for fixed expressions, and streaming for exports too big to hold in memory.

## Strings in .NET never change A `string` in C# is an instance of `System.String`, and it is **immutable**: once the runtime has created it, no method, operator or property can change its characters. Every member that looks like it edits text returns its result as a string instead: - `Trim()`, `ToUpper()`, `Replace(...)`, `Substring(...)` and `Insert(...)` return a new instance whenever the text changes, and they never touch the original. - A statement such as `name.Trim();` that ignores the result does nothing useful; code analysis rule **CA1806** flags it, but in .NET 10 it is enabled only as a suggestion, so a normal build stays quiet. - Assigning to a variable (`name = name.Trim();`) only points the variable at the new object. Immutability is what makes strings safe to share between threads, to use as dictionary keys and to hand to any method without a defensive copy. Its price shows up when text is built piece by piece. ## What `csv += line` compiles to The compound assignment is shorthand for `csv = csv + line`, and the compiler lowers `+` on two strings to a call to `string.Concat(string, string)`. That method sums the two lengths, allocates a brand-new string of that size and copies both inputs into it. Nothing is appended in place, and the compiler does **not** quietly switch a loop to `StringBuilder`: the compiled loop body is the same two-argument `Concat` call on every pass. ## How the cost adds up Picture the export loop for 200,000 lines of about 21 characters each: 1. Pass 1 allocates a string of 21 characters. 2. Pass 2 allocates 42 characters and copies the first 21 again. 3. Pass k allocates about 21·k characters and copies all of them. 4. Summed over n passes, the copying is about n²/2 lines' worth, so doubling the row count roughly quadruples the work. Measured on .NET 10 with `GC.GetAllocatedBytesForCurrentThread()` around each loop, 20,000 rows were already enough to make the difference plain: | Approach | Result length | Bytes allocated | |---|---|---| | `csv += line` | 426,580 chars | about 8.4 GB | | `StringBuilder.Append` + `ToString()` | 426,580 chars | about 3 MB | There is a second cost: a `string` of 42,500 characters or more is at least 85,000 bytes, the threshold at which the runtime allocates on the **large object heap**, so every later intermediate string goes there. How that heap is collected is a topic for the material on the garbage collector; here it is enough that the loop keeps feeding it garbage. ## What StringBuilder does instead `System.Text.StringBuilder` is a mutable text buffer designed for this job: - **`Append`** copies only the characters you pass into spare room in the current buffer. - **When the buffer is full**, the builder links in a new chunk; existing characters are not moved, so growth costs no recopy of earlier text. - **`ToString()`** allocates one string of exactly `Length` characters and copies every chunk into it once. - **Chaining** works because `Append` returns the same builder: `sb.Append(id).Append(',').Append(sku)`. Each line's characters are therefore copied twice in total, once by `Append` and once by `ToString()`, however many lines there are. ```csharp var sb = new StringBuilder(); foreach (Order o in orders) sb.Append(o.Id).Append(',').Append(o.Sku).Append(',').Append(o.Quantity).Append('\n'); string csv = sb.ToString(); ``` The `Append(int)` and `Append(char)` overloads write the value directly instead of first creating a separate string for it. ## When `+=` is fine and when neither is right - **A fixed, small number of parts** in one expression (`a + "," + b`) compiles to a single `Concat` call that allocates once; a `StringBuilder` would only add overhead. - **A handful of iterations** with short strings costs microseconds either way; the quadratic term matters when the count grows with the data. - **Very large output** such as a 200,000-line export often should not live in one string at all: writing each line to a file or network stream avoids holding the whole document in memory, and streams are covered with the .NET runtime material. The interview answer in one breath: strings are immutable, so `+=` in a loop is a new allocation and a full copy per pass, which grows quadratically; `StringBuilder` appends into a growable buffer and copies once at the end.

  • Why does `name.Trim();` on its own line leave `name` unchanged, and does anything warn about it?
    `Trim` returns a new string and the statement throws it away, so `name` still refers to the original. Write `name = name.Trim();`. Code analysis rule CA1806 reports a discarded string result, but in .NET 10 it is enabled only as a suggestion, so an ordinary build prints no warning for it.
  • If all the lines are already in a `List<string>`, is `string.Join` better than a StringBuilder?
    Yes. `string.Join("\n", lines)` reads a `List<string>` or an array as a span, sums the lengths and separators, allocates the result once and copies each line once, with no builder object. The catch is holding 200,000 line strings first; when lines are produced one at a time, appending each to a StringBuilder, or writing it to a stream, avoids keeping them all.
  • Does the C# compiler ever turn `+=` inside a loop into StringBuilder calls?
    No. The compiler flattens a single expression such as `a + b + c` into one `string.Concat` call, but it does not rewrite a loop. Each pass of `s += part` stays a separate `string.Concat(string, string)` call that allocates a new string, so the choice of StringBuilder is yours to make.

Building with += is like retyping the whole letter on fresh paper every time you add a sentence; a StringBuilder is a notebook you keep writing in, adding pages when one fills, and you make one clean copy at the end.

  • The compiler quietly turns += in a loop into a StringBuilder.
  • Calling name.Trim() changes the string that name refers to.
  • Appending to a string grows it in place, the way List<T>.Add does.
  • StringBuilder is always faster, even for joining two or three strings in one expression.
  • StringBuilder.ToString() returns its internal buffer without copying.
open as a page

In a C# interpolated string such as $"{amount,10:N2}", what do the 10 and the N2 do, and what if the value is wider?

level: juniorimportance: must knowfreq 62%

basics

~20 s

In a hole {expr,width:format}, the comma number is a minimum width (positive right-aligns, negative left-aligns) and the colon text is the value's format string, here two-decimal N2. A wider value is printed in full, never truncated.

open as a page

In C#, why does the string "👍" report a Length of 2, and what does string.Length actually count?

level: juniorimportance: must knowfreq 50%

basics

~20 s

A C# char is one UTF-16 code unit and string.Length counts code units. The thumbs-up emoji is U+1F44D, above U+FFFF, so UTF-16 stores it as a surrogate pair of two chars and Length reports 2.

open as a page

In C#, what does the compiler emit for `id + "," + sku + "," + qty`, and when is `+` cheaper than StringBuilder?

level: middleimportance: must knowfreq 60%

basics

~20 s

One string.Concat call per expression: up to four operands use fixed-arity overloads, five or more go in a string array, and adjacent constants fold at compile time. Fixed parts allocate once; StringBuilder wins only when parts arrive in a loop.

open as a page

In .NET, which StringComparison value should you pass when matching usernames, file extensions or protocol tokens, and which for text shown to people?

level: middleimportance: must knowfreq 70%

basics

~10 s

Use StringComparison.Ordinal, or OrdinalIgnoreCase when case should not matter, for usernames, file extensions, paths, keys and protocol tokens. Use CurrentCulture or CurrentCultureIgnoreCase only for text people read, such as sorting a displayed list.

open as a page

In C#, why can $"{total:N2}" print 1,234.50 on one server and 1.234,50 on another, and how do you pin the output?

level: middleimportance: must knowfreq 56%

basics

~10 s

Interpolation formats each hole with CultureInfo.CurrentCulture when the line runs, so N2 takes that culture's separators. Pin it with string.Create(CultureInfo.InvariantCulture, $"..."), FormattableString.Invariant, or ToString(format, provider).

open as a page

In C#, how do `string.IsNullOrEmpty` and `string.IsNullOrWhiteSpace` differ, and does writing `string.Empty` instead of `""` change anything?

level: juniorimportance: should knowfreq 55%

basics

~20 s

IsNullOrEmpty is true only for null or a zero-length string; IsNullOrWhiteSpace is also true when every character is white space, such as spaces, tabs or line breaks. string.Empty and "" are one instance; only "" is a constant.

open as a page

In .NET, what does passing a capacity to `new StringBuilder(int)` save, given that a full StringBuilder grows by adding chunks?

level: middleimportance: should knowfreq 40%

basics

~20 s

A StringBuilder starts with 16 chars of room; when full it links a new chunk sized to the current length (at most 8,000) or the request if larger, without copying old text. A right-sized capacity gives one buffer, no slack and a single-chunk ToString.

open as a page

In .NET, which string methods compare with the current culture when you pass no StringComparison, and which compare ordinally?

level: middleimportance: should knowfreq 50%

basics

~10 s

Ordinal by default: ==, Equals, Contains, Replace and every char overload. Current culture by default: CompareTo, string.Compare, StartsWith(string), EndsWith(string), IndexOf(string) and LastIndexOf(string), plus ToUpper and ToLower casing and List<string>.Sort().

open as a page

How do you make a C# Dictionary<string, TValue> or HashSet<string> match keys case-insensitively, and why pass StringComparer.OrdinalIgnoreCase instead of lowercasing keys?

level: middleimportance: should knowfreq 55%

basics

~10 s

Pass StringComparer.OrdinalIgnoreCase to the constructor: new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase). It hashes and compares case-insensitively with no allocations, keeps the original key spelling, and avoids the culture traps of ToLower().

open as a page

In C#, how do a verbatim string @"..." and a raw string literal """...""" differ for paths, quotes and multi-line JSON?

level: middleimportance: should knowfreq 40%

basics

~20 s

A verbatim @"..." ignores backslash escapes, but a quote is written "" and source indentation stays in the text. A raw literal (C# 11) has no escapes at all, and its multi-line form strips the closing delimiter's indentation.

open as a page

In .NET, what does string.EnumerateRunes() give you that a foreach over the string's chars does not, and where does a Rune still fall short?

level: middleimportance: should knowfreq 35%

basics

~20 s

EnumerateRunes yields System.Text.Rune values, one per Unicode scalar value, so a surrogate pair arrives as one item and a lone surrogate as U+FFFD. A flag, a ZWJ emoji or an accented letter can still span several runes.

open as a page

In C#, which strings are interned automatically, what do `string.Intern` and `string.IsInterned` do, and why is interning user data rarely right?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Literals, including constant expressions the compiler folds, are interned; strings built at run time are not. string.Intern returns the pooled instance, adding the string if absent; IsInterned returns it or null. Pooled strings stay alive for the process.

open as a page

A C# role check written as role.ToUpper() == "ADMIN" passes in tests but fails on servers whose culture is tr-TR — why, and how do you fix it?

level: seniorimportance: should knowfreq 45%

basics

~10 s

String.ToUpper() uses the current culture, and Turkish uppercases i to the dotted İ (U+0130), so "admin" becomes "ADMİN". Compare with string.Equals(role, "admin", StringComparison.OrdinalIgnoreCase) or use ToUpperInvariant().

open as a page

In C#, how can a custom interpolated string handler make trace.Write($"Rendering {Describe()}") skip all formatting when tracing is off?

level: seniorimportance: should knowfreq 33%

basics

~20 s

Since C# 10, a $"" passed to a handler-typed parameter becomes a handler constructor call plus AppendLiteral and AppendFormatted calls. A constructor that gets the receiver through [InterpolatedStringHandlerArgument("")] and sets out bool shouldAppend to false skips every hole.

open as a page

In a C# chat app, two nicknames both display as "José" yet == says they differ; why, and how does string.Normalize fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Unicode stores é either as one precomposed code point (U+00E9) or as e plus U+0301 COMBINING ACUTE ACCENT; == compares UTF-16 code units ordinally, so they differ. Normalizing both with string.Normalize(), which uses FormC, makes them equal.

open as a page

A C# chat app builds 40-character message previews with message.Substring(0, 40), and some previews end in a garbled symbol; why, and how do you truncate safely?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Substring counts UTF-16 code units, so index 40 can fall inside a surrogate pair or a multi-rune emoji; a lone half is encoded as U+FFFD. Truncate by text elements with a StringInfo.GetNextTextElementLength loop instead.

open as a page

As the lead setting C# conventions, what default would you choose for string comparison, and would you make CA1307, CA1309, CA1310 and CA1311 build errors?

level: principalimportance: should knowfreq 30%

basics

~20 s

A sound default is ordinal comparison for everything except text shown to people, with every call naming its StringComparison. CA1310 and CA1311 are cheap, high-signal build errors; CA1307 and CA1309 add noise and suit only codebases wanting every comparison explicit.

open as a page

In C# 11 and later, what does a "PING"u8 literal produce, and when would you use it instead of Encoding.UTF8.GetBytes?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

A u8 suffix makes the compiler encode the literal to UTF-8 at compile time and type it as ReadOnlySpan<byte>, so the call site allocates nothing. Use it for fixed protocol text; use Encoding.UTF8.GetBytes for strings known only at run time.

open as a page

In .NET, how does `string.Create<TState>(int, TState, SpanAction<char, TState>)` build a URL slug without an intermediate buffer, and what must its callback respect?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

string.Create allocates the final string once at the given length and hands its characters to your callback as a Span<char>. You need the exact length first, must write every slot, and should pass inputs as state to a static lambda.

open as a page

When a C# code generator embeds JSON with interpolated values in a raw string literal, why use $$""" and how many braces open a hole?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

The count of $ signs sets how many braces delimit a hole: under $$, {{expr}} is a hole and single braces are text, so JSON needs no escaping. Doubling braces does not escape them in raw literals (CS9006).

open as a page