C# String
Learn about the string type in C#, how strings are created, and commonly used string operations.
What is a String?
A string in C# is a sequence of characters treated as a single object, and it is represented internally as an immutable reference type.
Creating Strings
Strings can be created directly using string literals in double quotes, or built dynamically using classes like StringBuilder for frequent modifications.
String Immutability
Once a string is created, its value cannot be changed; any operation that appears to modify a string actually creates a new string object in memory.
Common String Operations
C# provides many built-in methods for strings, such as concatenation, substring extraction, searching, and case conversion, making text manipulation straightforward.
Ways to Write String Literals
C# offers several literal forms, each solving a different annoyance:
string name = "Arjun";
int score = 92;
string plain = "Line one\nLine two"; // escape sequences
string path = @"C:\Reports\March\data.csv"; // verbatim: backslashes are literal
string message = $"Hi {name}, you scored {score}%"; // interpolation
string padded = $"{name,-10}|{score,5}"; // alignment inside interpolation
string json = """
{ "name": "Arjun", "active": true }
"""; // raw string literal (C# 11+)
Interpolation is usually the clearest way to build text from variables. Raw string literals are ideal for JSON, SQL or HTML snippets because quotes and backslashes need no escaping.
Worked Example: Cleaning and Inspecting Input
Suppose a user types an email address with spaces and mixed case. The common string methods tidy and examine it:
string raw = " Arjun.Mehta@Example.COM ";
string email = raw.Trim().ToLowerInvariant(); // "arjun.mehta@example.com"
int at = email.IndexOf('@'); // 11
string user = email.Substring(0, at); // "arjun.mehta"
string domain = email[(at + 1)..]; // "example.com" (range syntax)
bool isCompany = domain.EndsWith("example.com");
string display = user.Replace(".", " "); // "arjun mehta"
string[] parts = "red,green,blue".Split(',');
string joined = string.Join(" | ", parts); // "red | green | blue"
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // True
Every call above returns a new string. The original raw variable still holds the untrimmed text, which is immutability in action.
Comparing Strings Correctly
For string, the == operator compares content, not references, so "abc" == "abc" is true. Case and culture are where bugs appear. Pass a StringComparison value to make the intent explicit:
bool same = string.Equals("Admin", "ADMIN", StringComparison.OrdinalIgnoreCase); // True
bool hasWord = "Order Confirmed".Contains("confirmed", StringComparison.OrdinalIgnoreCase);
int order = string.Compare("apple", "banana", StringComparison.Ordinal); // negative
Use ordinal comparisons for identifiers, file names and keys. Use culture-aware comparisons only when sorting text shown to people.
Performance Notes and Frequent Mistakes
When to reach for StringBuilder
Because each concatenation creates a new object, building a long string inside a loop with += repeatedly copies everything built so far. StringBuilder keeps an internal buffer that grows as needed:
var sb = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
sb.Append("Row ").Append(i).AppendLine();
}
string report = sb.ToString();
For a handful of joins, plain concatenation or interpolation is perfectly fine and easier to read. Switch to StringBuilder when the number of appends is large or unknown.
Frequent mistakes
- Calling a method and ignoring its result, such as
name.Trim();on its own line, then wondering why nothing changed. - Using
ToUpper()to compare text instead of a case-insensitive comparison. - Calling methods on a
nullstring; check withstring.IsNullOrEmptyor use the?.operator first. - Passing a length that runs past the end in
Substring, which throwsArgumentOutOfRangeException. - Forgetting that
stringandStringare the same type; the lowercase keyword is the usual style. - Building SQL queries by gluing user input into strings. Use parameterised commands instead, because concatenated input can change the meaning of the query.
- Formatting numbers and dates for users without thinking about culture. A value like 1,234.50 is written differently in other regions, so pass
CultureInfo.InvariantCulturewhen text must be machine-readable.
A short self-test: given a full name with extra spaces, can you trim it, split it into first and last names, capitalise each part and join it back with one space? If that feels easy, you are comfortable with the core string toolkit.