skip to content

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%

answer

  1. literals share one instance
  2. constant folding counts as literal
  3. use the return value
  4. the pool never shrinks

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.

solid answer

~50 s

The runtime keeps an intern pool, a table of unique string instances. Every string literal in your code ends up there, so two occurrences of `"order-42"` anywhere in the program are the same object. A constant expression such as `Prefix + "42"` with `const string Prefix` is folded by the compiler into a literal, so it is interned too; `"order-" + id` built when the code runs is a new object with equal characters. `string.Intern(s)` looks up an equal string and returns the pooled instance, adding `s` if none exists; you must use its return value. `string.IsInterned(s)` returns the pooled instance or `null` without adding anything. Interning user data is rarely right: the pool keeps its strings reachable for as long as the process runs, `==` already compares characters, and the pool is shared by every component. A scoped `HashSet<string>` pool deduplicates without leaking.

code

csharp · 15 lines
csharp
const string Prefix = "order-";
string fromLiterals = Prefix + "42";            // folded by the compiler into the literal "order-42"
string id = 42.ToString();
string atRunTime = "order-" + id;               // built by string.Concat when the line runs

Console.WriteLine(ReferenceEquals(fromLiterals, "order-42"));        // True
Console.WriteLine(ReferenceEquals(atRunTime, "order-42"));           // False
Console.WriteLine(atRunTime == "order-42");                          // True: == compares characters

string pooled = string.Intern(atRunTime);
Console.WriteLine(ReferenceEquals(pooled, "order-42"));              // True
Console.WriteLine(ReferenceEquals(pooled, atRunTime));               // False

string fresh = new string('x', 3) + "-never-a-literal";
Console.WriteLine(string.IsInterned(fresh) is null);                 // True

go deeper

for a junior

Recall that string literals are shared instances and that == on strings compares characters, so equal strings compare equal whether or not they are the same object.

for a middle

Explain which strings are interned: literals and folded constants yes, run-time results no; then what Intern and IsInterned return, and why the return value matters.

for a senior

Argue against interning user data: process-lifetime retention, a process-wide shared table, hashing cost per call and lock sharing; offer a scoped HashSet<string> pool for batch deduplication.

for a principal

Treat deduplication as a measured memory decision: profile repeated values first, prefer a pool with an owner and a lifetime, and keep string.Intern for small, bounded, truly static sets.

## What the runtime interns for you **Interning** means keeping one shared instance per distinct string value, so that equal strings can be the same object. The .NET runtime keeps such a table, the **intern pool**, and fills it in two ways: - **Literals.** Every string literal in your code resolves to a pooled instance, so `"order-42"` written in two different methods is the same object. - **Explicit calls.** `string.Intern(s)` adds a string you built at run time. Nothing else is interned automatically. Strings returned by `string.Concat`, `StringBuilder.ToString()`, `Substring`, file reads or deserialisers are normally new objects, even when their characters match a literal. ## Constant folding decides which side you are on Whether a concatenation produces an interned string depends on whether the compiler can compute it: | Code | Interned? | Why | |---|---|---| | `"order-42"` | yes | a literal | | `Prefix + "42"` with `const string Prefix = "order-"` | yes | folded at compile time into the literal `"order-42"` | | `"order-" + id` with `string id = 42.ToString()` | no | `string.Concat` runs when the line executes | | `string.Intern("order-" + id)` | the returned value is | it is the pooled `"order-42"` | That is why `ReferenceEquals(Prefix + "42", "order-42")` prints `True` while `ReferenceEquals("order-" + id, "order-42")` prints `False`, even though `==` reports both pairs equal. `==` on two `string` operands compares characters; reference identity is visible only through `ReferenceEquals` or a cast to `object`. ## string.Intern and string.IsInterned Both are static methods on `System.String`, and both throw `ArgumentNullException` for a null argument: 1. **`string.Intern(string str)`** returns the pooled instance equal to `str`. If none exists, it adds `str` itself and returns it. The argument variable is not changed, so `string.Intern(s);` on its own line achieves nothing; write `s = string.Intern(s);`. 2. **`string.IsInterned(string str)`** returns the pooled instance if one exists and `null` otherwise. It never adds anything, which makes it a lookup, not a deduplication tool. The returned reference is the point: after `s = string.Intern(s)`, every caller holding the pooled instance shares one object, so a million equal values cost one string. ## Why interning user data is rarely right - **The pool only grows.** In a test, a string passed to `string.Intern` was still alive after its last reference was dropped and `GC.Collect()` ran, while an equal un-interned string was collected. For ordinary application code the pool keeps its entries for the life of the process, so interning request IDs, user names or log fields is a slow leak. - **It is process-wide.** The pool is shared by every library in the process; you cannot scope it to one job or clear it. - **The lookup is not free.** Each `Intern` call hashes the whole string and searches the table, a cost you pay even when the value is unique. - **`==` does not need it.** String equality already compares characters, so interning to make comparisons work is a misunderstanding. `string.Equals` does take a fast path when both references are the same object, but that rarely justifies the costs above. - **Locks get shared.** Because literals are interned, `lock ("orders")` in two unrelated components is the same lock; the C# docs list string instances among objects not to lock on. ## Deduplicating without the intern pool When a batch job really does see the same values over and over, such as SKUs repeated across 200,000 order lines, a pool you own gives the memory saving without the leak. `HashSet<string>.TryGetValue(T, out T)` returns the stored instance equal to the probe: ```csharp var pool = new HashSet<string>(StringComparer.Ordinal); string Dedup(string value) { if (pool.TryGetValue(value, out string? existing)) return existing; pool.Add(value); return value; } ``` When the job ends, dropping or clearing `pool` lets every string in it be collected. The ordinal comparer keeps the pool's notion of equal identical to `string.Equals`. In an interview, say that literals and folded constants are interned, run-time strings are not, `Intern` returns the shared instance and must be assigned, and that the process-lifetime pool makes interning untrusted or unbounded data a liability.

  • Why must you use the return value of `string.Intern(s)`?
    `Intern` does not turn `s` into the pooled object; it returns a reference to the pooled one, which is a different object whenever an equal string was already there. Code that calls `string.Intern(s);` and keeps using `s` gets none of the sharing, only the cost of the lookup.
  • Why is `lock` on a string a bad idea?
    String literals are interned, so every `lock ("orders")` in the process, in your code or a library's, locks the same object, and unrelated code can contend or deadlock without knowing why. The C# documentation lists string instances among the objects not to lock on; a private `object` field keeps the lock yours.
  • Does a string built with `+` from literals only ever get interned?
    Only when every operand is a compile-time constant, so the compiler folds the expression into a literal. As soon as one operand is a variable, a method call or a `static readonly` field, the concatenation runs at run time and returns a new, un-interned string.

  • Every string with the same characters is automatically the same object.
  • string.Intern(s) changes s to refer to the pooled copy.
  • == compares string references, so strings must be interned for == to match.
  • Interned strings are collected once nothing else references them.
  • A concatenation of literals and const fields is built at run time, so it is never interned.