Skip to content
Tutorials Center
My learning

Topics

C# Reference Β· Types and Literals

C# string type

Reference for the C# string type: immutability, literals, interpolation, raw and verbatim strings, equality, null versus empty, and performance tips.

string (System.String) is an immutable sequence of UTF-16 char values. It is a reference type, but it behaves like a value in most code: once created, its contents never change, and every "modification" such as Replace or ToUpper returns a new string. Equality (==) compares the text, not the reference.

Strings can be written as regular literals ("a\tb"), verbatim literals (@"C:\temp"), interpolated strings ($"Hi {name}"), raw string literals ("""...""") and UTF-8 literals ("abc"u8). The null value and the empty string "" are different things; the second is a valid string of length zero.

C#
string name = "Ada";
string greeting = $"Hello, {name}!";

Try it

C# Literals and immutability

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.

C# null, empty and common operations

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.

Syntax

C#
string s1 = "text";                 // regular literal
string s2 = @"a\b";                 // verbatim: backslash is literal, "" for a quote
string s3 = $"{x}";                 // interpolated
string s4 = $@"{x}\n";              // both
string s5 = """raw "quotes" here""";   // raw string literal
ReadOnlySpan<byte> utf8 = "abc"u8;     // UTF-8 literal
Member Description
Length, indexer s[i], s[range] Count of char values, one char, a substring.
Substring, Split, Join, Replace, Trim, PadLeft, PadRight Create new strings.
Contains, StartsWith, EndsWith, IndexOf, LastIndexOf Search. Pass a StringComparison for clarity.
ToUpperInvariant, ToLowerInvariant Culture-independent case conversion.
string.IsNullOrEmpty, string.IsNullOrWhiteSpace Null/blank checks.
string.Concat, string.Format, string.Create Build strings.
string.Compare, Equals, CompareOrdinal Comparison with explicit rules.

Errors. An index outside the string throws IndexOutOfRangeException (indexer) or ArgumentOutOfRangeException (Substring). Calling a method on null throws NullReferenceException.

Usage notes

  • Immutability makes loops expensive. s += x in a loop allocates a new string each time, giving O(nΒ²) copying. Use StringBuilder or string.Join for many pieces.
  • Always choose a comparison. Equals, Compare and IndexOf have culture-sensitive defaults for some overloads. Use StringComparison.Ordinal or OrdinalIgnoreCase for identifiers, paths and protocols.
  • Globalization is invariant here. On our runner every culture behaves as invariant, so culture-sensitive comparisons match ordinal for most inputs; do not assume that on a real server.
  • Interning. Literals in the same assembly are interned, so equal literals share one object. Never rely on reference equality for strings.
  • Strings are UTF-16. Length counts code units, not characters a reader sees. Emoji count as 2.
  • null in concatenation becomes the empty string, but null.Length crashes. With nullable reference types on, declare optional text as string?.
  • Spans avoid copies. AsSpan() and ReadOnlySpan<char> slice without allocation.
  • Composite format. string.Format("{0}", x) and interpolation both call ToString()/IFormattable.