System.String Class

Namespace: System

Overview

Represents text as a sequence of characters.

The System.String class is the fundamental type for representing text in .NET. Strings in .NET are immutable, meaning once a string object is created, its value cannot be changed. Any operation that appears to modify a string actually creates a new string object with the modified value. This immutability ensures thread safety and predictable behavior.

The String class provides a rich set of methods for string manipulation, comparison, searching, and formatting.

Members

The String class has numerous members, including constructors, properties, methods, and operators. Here are some of the most commonly used members:

Properties

Constructors

Methods

Operators

Syntax


public sealed class String : IComparable<string>,
    ICloneable,
    IConvertible,
    IEnumerable<char>,
    IEnumerable,
    IList<char>,
    ICollection<char>,
    IReadOnlyList<char>,
    IReadOnlyCollection<char>
            

The String class is declared as sealed, meaning it cannot be inherited from. It implements several interfaces for comparison, conversion, and collection access.

Remarks

Immutability: As mentioned, strings are immutable. Operations like concatenation, replacement, or case conversion return new string objects rather than modifying the original. This design choice is crucial for performance and correctness, especially in multi-threaded environments.

String Pooling: The .NET runtime often uses string interning (string pooling) to improve performance. When a string literal is encountered, the runtime checks if a string with the same value already exists in the pool. If it does, a reference to the existing string is returned. Otherwise, a new string is created and added to the pool. This means that multiple identical string literals might actually refer to the same string object in memory.

Performance Considerations: While immutable strings are safe and convenient, frequent string manipulations (especially in loops) can lead to the creation of many temporary string objects, impacting performance and memory usage. For scenarios requiring extensive string modification, consider using mutable string types like System.Text.StringBuilder.

Null vs. Empty Strings: Be mindful of the distinction between a null string (null) and an empty string (""). A null string references no object, while an empty string references a valid String object with zero characters. Many string methods will throw a NullReferenceException if called on a null string.

Examples

Creating Strings


string greeting = "Hello, World!";
char[] chars = {'C', '#', ' ', 'i', 's', ' ', 'f', 'u', 'n'};
string fromChars = new string(chars);
string repeatedChar = new string('X', 5); // "XXXXX"

Console.WriteLine(greeting);
Console.WriteLine(fromChars);
Console.WriteLine(repeatedChar);
            

String Manipulation


string original = "  Trim me!  ";
string trimmed = original.Trim(); // "Trim me!"
string upper = trimmed.ToUpper(); // "TRIM ME!"
string lower = upper.ToLower(); // "trim me!"
string replaced = lower.Replace("me", "you"); // "trim you!"

Console.WriteLine($"Trimmed: '{trimmed}'");
Console.WriteLine($"Uppercase: {upper}");
Console.WriteLine($"Lowercase: {lower}");
Console.WriteLine($"Replaced: {replaced}");
            

String Comparison


string str1 = "apple";
string str2 = "Apple";
string str3 = "banana";

// Case-sensitive comparison
bool areEqualCaseSensitive = (str1 == str2); // false
bool areEqualOrdinal = String.Equals(str1, str2, StringComparison.Ordinal); // false

// Case-insensitive comparison
bool areEqualCaseInsensitive = str1.Equals(str2, StringComparison.OrdinalIgnoreCase); // true

// Using CompareTo
int comparison = str1.CompareTo(str3); // negative value, as "apple" comes before "banana"

Console.WriteLine($"'{str1}' == '{str2}' (case-sensitive): {areEqualCaseSensitive}");
Console.WriteLine($"'{str1}' == '{str2}' (Ordinal): {areEqualOrdinal}");
Console.WriteLine($"'{str1}' == '{str2}' (OrdinalIgnoreCase): {areEqualCaseInsensitive}");
Console.WriteLine($"'{str1}'.CompareTo('{str3}') = {comparison}");
            

String Formatting


string name = "Alice";
int age = 30;

string formattedString = String.Format("My name is {0} and I am {1} years old.", name, age);
Console.WriteLine(formattedString);

// Using string interpolation (C# 6+)
string interpolatedString = $"My name is {name} and I am {age} years old.";
Console.WriteLine(interpolatedString);