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.
The String class has numerous members, including constructors, properties, methods, and operators. Here are some of the most commonly used members:
Gets the number of characters in the current String object.
String() String()
Initializes a new instance of the String class. (This is an internal constructor and not directly accessible for instantiation.)
String(char) String(char c)
Initializes a new instance of the String class to the value indicated by a specified Unicode character. This constructor is used internally to create strings of repeated characters.
String(char[]) String(char[] value)
Initializes a new instance of the String class to the value indicated by a specified array of Unicode characters.
int CompareTo(string str)
Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, occurs later than, or occurs at the same position as the other object in sort order.
| Name | Type | Description |
|---|---|---|
| str | string | The object to compare with the current instance. |
bool Contains(string value)
Determines whether the string contains a specified substring.
| Name | Type | Description |
|---|---|---|
| value | string | The string to seek. |
string Format(string format, object arg0)
Formats a string by using the specified format and arguments. This is a static method for creating formatted strings.
| Name | Type | Description |
|---|---|---|
| format | string | The format string (e.g., "Hello, {0}!"). |
| arg0 | object | The argument to format. |
string Substring(int startIndex)
Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.
| Name | Type | Description |
|---|---|---|
| startIndex | int | The zero-based starting character position of the substring. |
string ToLower()
Converts the current string to lowercase.
string ToUpper()
Converts the current string to uppercase.
string operator + (string a, string b)
Concatenates two strings.
bool operator == (string a, string b)
Compares two strings for equality. This operator performs a value comparison.
bool operator != (string a, string b)
Compares two strings for inequality. This operator performs a value comparison.
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.
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.
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 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 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 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);