Strings in C#

8 questions found

What is the difference between string keyword and System.String class?

Beginner
The string keyword in C# is simply an alias for the System.String class provided by the language for convenience, meaning both refer to exactly the same type and can be used interchangeably. There is no functional difference between them, but developers commonly use the lowercase string keyword for everyday coding and reserve System.String for situations like reflection or when being explicit about the full type name.
string name1 = "Ali";
System.String name2 = "Ali";
// Both lines create the exact same type
Real-world example A code style guide at a company recommends always using the lowercase string keyword instead of System.String, purely for consistency and readability, since both compile to the exact same underlying type.

Common follow-ups: Are there other C# keywords that alias BCL types the same way string aliases System.String?;Does using string instead of System.String affect performance in any way?

Are string objects mutable or immutable in C#?;What is the difference between System.Text.StringBuilder and System.String?

Are string objects mutable or immutable in C#?

Beginner
String objects in C# are immutable, meaning that once a string is created, its actual content in memory can never be changed. Any operation that appears to modify a string, such as concatenation or replacing characters, actually creates a brand new string object in memory and leaves the original string untouched, which is an important detail to understand when reasoning about performance and memory usage in string heavy code.
string greeting = "Hello";
greeting = greeting + " World";
// This creates a new string object, the original "Hello" is unchanged in memory
Real-world example A developer investigating a memory heavy application discovers that thousands of string concatenations inside a loop were each creating a brand new string object, and switches to StringBuilder to avoid this repeated allocation.

Common follow-ups: Why does C# make strings immutable instead of mutable?;What is the performance impact of repeated string concatenation?

What do you mean by String objects are immutable?;What is the difference between System.Text.StringBuilder and System.String?

What do you mean by String objects are immutable?

Beginner
Saying that string objects are immutable means the actual character data stored inside a string object cannot be altered after it has been created in memory. When you assign a new value to a string variable or perform an operation like ToUpper or Replace, C# creates an entirely new string object in memory and simply points your variable to that new object, rather than changing the characters of the original string in place.
string original = "redis";
string upper = original.ToUpper();
// original still equals "redis", upper is a completely separate new string object
Real-world example A caching system safely shares the same string object across multiple threads without any risk of one thread accidentally changing its value, since the immutability of strings guarantees the content can never be modified after creation.

Common follow-ups: How does string immutability relate to thread safety?;Does string interning relate to immutability?

Are string objects mutable or immutable in C#?;What is the difference between string keyword and System.String class?

What is a verbatim string literal and why do we use it?

Beginner
A verbatim string literal in C# is created by placing an at symbol directly before the opening quotation mark, and it tells the compiler to treat the string exactly as written, ignoring normal escape sequences like backslash n for a new line. Verbatim strings are especially useful for file paths, regular expressions, and multi line text, since they let you write backslashes and line breaks directly without needing to escape every special character.
string path1 = "C:\\Users\\Test\\file.txt";
string path2 = @"C:\Users\Test\file.txt";
// Both represent the same file path
Real-world example A developer writing a file processing utility uses a verbatim string literal to store a Windows file path, avoiding the need to escape every single backslash character in the path manually.

Common follow-ups: Can a verbatim string literal span multiple lines?;How do you include an actual quotation mark inside a verbatim string?

How do you create empty strings in C#?;What is the difference between an implicit conversion and an explicit conversion?

How do you create empty strings in C#?

Beginner
You can create an empty string in C# in a few equivalent ways, including assigning two double quotation marks with nothing between them, using the built in String.Empty field, or calling the String constructor with an empty character array, all of which produce a string containing zero characters. String.Empty is often preferred in professional code since it clearly communicates intent and avoids allocating a brand new string literal each time.
string empty1 = "";
string empty2 = string.Empty;
bool isEmpty = empty1 == empty2; // true
Real-world example A form validation method initializes a variable to string.Empty before optionally assigning it a real value later, making it clear from the start that the variable represents an intentionally blank result if no value is ever assigned.

Common follow-ups: What is the difference between an empty string and a null string?;How do you check if a string is empty or only contains whitespace?

What is a verbatim string literal and why do we use it?;How do you determine whether a String represents a numeric value?

What is the difference between System.Text.StringBuilder and System.String?

Intermediate
System.String is immutable, meaning every modification creates a brand new string object in memory, which can become inefficient when you need to build up or modify text repeatedly, such as inside a loop. System.Text.StringBuilder, on the other hand, is a mutable class specifically designed for efficiently building and modifying text, since it can append, insert, or remove characters directly within its internal buffer without creating a new object every single time, making it significantly faster for heavy string manipulation scenarios.
var sb = new System.Text.StringBuilder();
for (int i = 0; i < 1000; i++) {
    sb.Append("Line " + i + "\n");
}
string result = sb.ToString();
Real-world example A log file generator that writes thousands of lines uses StringBuilder to efficiently assemble the entire log content in memory before writing it to disk once, avoiding the performance cost of creating a new string object for every single line.

Common follow-ups: When is it acceptable to use string concatenation instead of StringBuilder?;How does StringBuilder manage its internal memory buffer?

Are string objects mutable or immutable in C#?;What do you mean by String objects are immutable?

How do you determine whether a String represents a numeric value?

Beginner
You can determine whether a string represents a numeric value by using methods like int.TryParse, double.TryParse, or decimal.TryParse, which attempt to convert the string and return a boolean indicating success or failure without throwing an exception if the conversion fails. This approach is much safer than trying to parse the string directly and catching an exception, since exceptions are relatively expensive and checking with TryParse is both faster and cleaner.
string input = "123";
if (int.TryParse(input, out int number)) {
    Console.WriteLine($"Valid number: {number}");
} else {
    Console.WriteLine("Not a valid number");
}
Real-world example A form that accepts a user's age as text input uses int.TryParse to safely validate the entered value before saving it, immediately showing a friendly error message if the user typed letters instead of digits.

Common follow-ups: What is the difference between int.Parse and int.TryParse methods?;Are there similar TryParse methods for other data types like dates?

What is the difference between int.Parse and int.TryParse methods?;How do you create empty strings in C#?

What is the difference between int.Parse and int.TryParse methods?

Beginner
int.Parse converts a string to an integer but throws a FormatException if the string is not a valid number, or an OverflowException if the number is too large, which means you need to wrap it in a try catch block to handle invalid input safely. int.TryParse, on the other hand, attempts the same conversion but returns a boolean indicating whether it succeeded, placing the converted value into an out parameter, which avoids the performance cost and complexity of exception handling for something as common as invalid user input.
// Using Parse, requires try catch
try {
    int value = int.Parse("abc");
} catch (FormatException) {
    Console.WriteLine("Invalid number");
}

// Using TryParse, no exception needed
bool success = int.TryParse("abc", out int result);
Real-world example A checkout page that converts a user entered quantity into an integer uses TryParse instead of Parse, so an invalid entry like empty text simply results in a validation message rather than crashing the checkout process with an unhandled exception.

Common follow-ups: Why is TryParse generally considered more performant than Parse combined with a try catch?;Does TryParse work with types other than int?

How do you determine whether a String represents a numeric value?;What is the difference between System.Text.StringBuilder and System.String?