O'Reilly logo

C# Essentials by Peter Drayton, Ben Albahari, Brad Merrill

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required