C# Reference ยท Strings and Text
The String class
Overview of the C# string class: immutable UTF-16 text, the most useful members grouped by task, null handling, comparison rules and performance notes.
string (the C# keyword for System.String) is an immutable sequence of UTF-16 code units. It is a reference type with value-like behavior: == compares the text, and no method ever changes an existing string. Methods such as Replace or Trim return a new string and leave the original untouched.
This page is a map of the members you will use most, grouped by task, with links to the detailed pages. Create strings with literals ("text", @"verbatim", """raw"""), interpolation ($"{x}"), concatenation or StringBuilder.
string name = "Ada"; string greeting = $"Hello, {name}!"; Console.WriteLine(greeting.ToUpperInvariant());
Try it
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.
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
public sealed class String : IComparable<string>, IEquatable<string>, IEnumerable<char>, ICloneable string text = "value";
| Task | Members |
|---|---|
| Size and access | Length, indexer s[i], s[a..b] |
| Searching | IndexOf, LastIndexOf, IndexOfAny, Contains, StartsWith, EndsWith |
| Extracting | Substring, Split, Trim, TrimStart, TrimEnd |
| Changing (copies) | Replace, Insert, Remove, PadLeft, PadRight, ToUpper, ToLower |
| Combining | +, string.Concat, string.Join, string.Format, interpolation |
| Comparing | ==, Equals, string.Compare, CompareTo, StringComparison |
| Testing | string.IsNullOrEmpty, string.IsNullOrWhiteSpace |
| Converting | ToCharArray, Normalize, Encoding.UTF8.GetBytes |
Returns: members that change text return a new string; searching members return an index (-1 when not found) or a bool.
Errors: calling an instance member on a null string throws NullReferenceException. Index and length arguments outside the string throw ArgumentOutOfRangeException or IndexOutOfRangeException.
Usage notes
- Immutable. Building a string in a loop with
+=creates a new string on every step, which is O(n squared) overall. Use StringBuilder orstring.Joinfor many pieces. - Null versus empty.
""is a valid empty string;nullmeans no string. Nullable reference types make the difference visible:stringshould not be null,string?may be. - Equality is ordinal by default.
==andEquals(string)compare UTF-16 units exactly. Methods likeCompare,StartsWith(string)andIndexOf(string)use the current culture unless you pass aStringComparison. In this site's runner the culture is invariant, but on real machines it may not be. Always state the comparison explicitly for text that is not meant for display. - UTF-16 units, not characters. An emoji or a combined accent can take two or more
chars, soLengthcan be larger than what a reader sees. See Iterating characters and Text elements. - Maximum length. About one billion characters, limited by memory.
- Interning. Literals share a single instance per program; see String interning.
- Spans.
AsSpan()gives a no-copy view for parsing and slicing; see ReadOnlySpan of char. - Case. Use
ToUpperInvariant/ToLowerInvariantfor identifiers and keys, and culture-aware versions only for user-facing text.