Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 182 ยท Strings

Strings

Learn how C# strings work - immutability, creating strings, string vs String, null and empty checks, equality, StringComparison, ordinal vs culture rules and interning.

Text is everywhere in programs: names, messages, file paths, JSON, log lines. In C# all of that text is stored in objects of one type, string. It looks simple, but a few facts about it explain a surprising number of bugs and performance problems: strings are immutable, they are reference types that behave like values, and comparing them correctly depends on what you mean by equal.

This lesson builds the mental model. Later lessons use it: Working with Strings covers the methods, Interpolation and Formatting the formatting rules, and StringBuilder the efficient way to build large texts.

What a string is

A string is a sequence of UTF-16 code units, stored as char values (see booleans and chars). You can read its length with Length and any single character with the indexer, counting from zero.

C# Strings as sequences of chars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The index-from-end ^1 and the range 3..8 come from Ranges and Indices. Reading is allowed; assigning is not. word[0] = 'X' is a compile error, and that leads to the most important property of strings.

Strings are immutable

Once a string object exists, its characters never change. Every method that seems to modify a string, such as Replace, ToUpper or Trim, actually returns a new string and leaves the original alone.

C# Methods return new strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first call computes "HELLO" and discards it, which is a classic beginner mistake. The compiler cannot warn you, so remember to use the return value. The last line does not append to the old object either; it builds a new string and makes the variable original point to it. The old text becomes garbage for the collector.

Why did the designers choose immutability? There are good reasons:

  • Safety: you can pass a string anywhere without fear that the receiver changes it. Dictionary keys never change under the dictionary's feet.
  • Thread safety: many threads can read the same string without locks.
  • Sharing: the runtime can reuse identical literals (see interning below) and cache the hash code.
  • Security: a validated path or file name cannot be altered after validation.

The price is that repeated concatenation in a loop allocates a lot. StringBuilder exists for that case.

Creating strings

The common ways to get a string are literals, concatenation, interpolation, constructors and conversion methods.

C# Ways to create strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Escape sequences start with a backslash: \n for a new line, \t for a tab, \" for a quote, \\ for a backslash and \uXXXX for a Unicode code unit. For paths and multi-line text there are friendlier forms, covered in Raw, Verbatim and UTF-8 String Literals.

string versus String

string is a keyword; String is the class System.String. They are the same type. By convention, use the keyword for the type (string name) and the class name for static members (String.Join or string.Join, both fine; many teams pick one and enforce it with an analyzer).

C# string is an alias of System.String

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

null, empty and whitespace

A string variable can be in three very different states that beginners often mix up:

  • null: no string object at all.
  • "" (or string.Empty): a real string with length zero.
  • " ": a real string that contains only whitespace.

Calling a member on null throws a NullReferenceException, so you need to check first. The framework offers two helpers that cover almost every case: string.IsNullOrEmpty and string.IsNullOrWhiteSpace.

C# Three kinds of nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use IsNullOrWhiteSpace for user input (a name made of spaces is almost always an error) and IsNullOrEmpty when whitespace is meaningful. With nullable reference types enabled, the compiler also understands these helpers: after if (!string.IsNullOrEmpty(s)) it treats s as non-null inside the block. See Null operators for ?. and ??.

Prefer string.Empty or "" over null as the default for "no text yet" in your own types. It removes a whole class of null checks for callers.

Equality: what does "equal" mean?

The == operator on strings compares contents, not references, even though string is a reference type. That is a deliberate exception made by the language, and it is why "abc" == new string(['a','b','c']) is true. To compare references use object.ReferenceEquals.

C# Content equality versus reference equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The third and fourth lines show a trap. When both variables have the static type object, == is the reference operator, and the two different objects compare unequal even though their text is identical. Keep the static type string when you compare text.

Case, culture and StringComparison

Contents equal... but under which rules? Should "StraรŸe" equal "STRASSE"? Should "i" equal "I" in a Turkish locale, where uppercase i is ฤฐ? C# makes you choose with the StringComparison enum:

Value Meaning
Ordinal Compare the raw UTF-16 code units. Fast, exact, culture-free.
OrdinalIgnoreCase Like Ordinal, but letters differing only by (simple) case are equal.
InvariantCulture / InvariantCultureIgnoreCase Linguistic rules of the invariant culture.
CurrentCulture / CurrentCultureIgnoreCase Linguistic rules of the user's culture. Results can differ per machine.
C# Choosing a StringComparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The rule of thumb used by experienced developers:

  • Use Ordinal/OrdinalIgnoreCase for identifiers, file names, keys, protocol text, URLs, anything a program (not a human reader) interprets.
  • Use culture-aware comparison for text shown to and sorted for people, such as a list of names in a user interface.

Surprisingly, some string methods default to culture-sensitive rules (IndexOf(string), StartsWith(string), CompareTo) while others default to ordinal (Equals, ==, Contains, Replace). Passing the StringComparison explicitly removes the guesswork, and the analyzer rule CA1307/CA1309 can enforce it.

Ordering strings

string.Compare and CompareTo return a negative number, zero or a positive number. The sign is documented; the exact magnitude is not, so never compare against -1 or 1.

C# Comparing and sorting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Ordinal ordering sorts by code unit values, so every uppercase ASCII letter sorts before every lowercase one: "Z" comes before "a". That is predictable but not what humans expect, which is why user-facing sorting uses a culture-aware comparer such as StringComparer.CurrentCulture.

Interning: shared literals

Because strings are immutable, the runtime can safely store one copy of each identical literal and let all references share it. This is called interning. Literals in your source code are interned automatically; strings built at run time are not, unless you call string.Intern.

C# Interning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You almost never need to care. Always compare contents with == or Equals. Interning matters mainly as an explanation for why ReferenceEquals sometimes returns true for equal literals, and as a rarely useful memory saver when you hold millions of duplicates. Do not intern arbitrary user input: interned strings live as long as the process.

Common mistakes

  • Ignoring the return value of a string method.
  • Calling a member on a possibly-null string instead of checking or using ?..
  • Comparing with ToLower() == ToLower(): it allocates two strings and has culture pitfalls. Use string.Equals(a, b, StringComparison.OrdinalIgnoreCase).
  • Relying on culture-sensitive defaults for keys and file names.
  • Concatenating in a long loop (use StringBuilder).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the following code print? string s = "abc"; s.ToUpper(); Console.WriteLine(s);

    Strings are immutable. ToUpper returns a new string, and since the result was discarded, s still holds "abc".
  2. 2. Which check is true for a string that contains only spaces?

    A string of spaces is neither null nor empty, but IsNullOrWhiteSpace treats it as blank.
  3. 3. Two variables of static type object hold different string objects with identical text. What does == return?

    The content-comparing == is defined for the static type string. With static type object the reference operator is chosen, so use Equals or keep the string type.
  4. 4. Which comparison is best for checking file extensions such as ".TXT" against ".txt"?

    File names and extensions are machine-interpreted identifiers, so ordinal rules are right. OrdinalIgnoreCase is fast and does not allocate temporary strings.
  5. 5. Why can the runtime share one object between identical string literals?

    Nobody can change a string after creation, so interning identical literals is safe.

Summary

  • A string is an immutable sequence of UTF-16 chars; every "modifying" method returns a new string.
  • string and System.String are the same type; == compares contents when both sides are typed string.
  • Distinguish null, "" and whitespace; use IsNullOrEmpty and IsNullOrWhiteSpace.
  • Pick the rules with StringComparison: ordinal for identifiers, culture-aware for human-facing text.
  • Interning lets identical literals share one object; compare contents, not references.

Next: Working with Strings