Strings

C# offers a wide range of string-handling features. Support is provided for both mutable and immutable strings, extensible string formatting, locale-aware string comparisons, and multiple string encoding systems.

This section introduces and demonstrates the most common types you’ll use in working with strings. Unless otherwise stated, the types mentioned in this section all exist in the System or System.Text namespaces.

String Class

A C# string represents an immutable sequence of characters, and aliases the System.String class. Strings have comparison, appending, inserting, conversion, copying, formatting, indexing, joining, splitting, padding, trimming, removing, replacing, and searching methods. The compiler converts + operations on operands where the left operand is a string to Concat methods and preevaluates and interns string constants where possible.

Immutability of Strings

Strings are immutable, which means they can’t be modified after creation. Consequently, many of the methods that initially appear to modify a string actually create a new string:

string a = "Heat";
string b = a.Insert(3, "r");
Console.WriteLine(b); // Prints Heart

If you need a mutable string, see the StringBuilder class.

String Interning

In addition, the immutability of strings enable all strings in an application to be interned. Interning describes the process whereby all the constant strings in an application are stored in a common place, and any duplicate strings are eliminated. This saves space ...

Get C# Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.