Strings in C#: Immutability, StringBuilder and Comparison
Codevity Admin · 10/25/2026
Codevity Admin · 10/25/2026
Strings are the most used type in most programs and a favourite interview topic. Three ideas cover almost every question: immutability, , and comparison.
Once a object is created, its characters never change. Every method that seems to modify a string, such as , , and , returns a new string and leaves the original alone.
Why immutable?
Each creates a new string and copies all the characters so far. Building a long string in a loop does O(n squared) copying and creates many short-lived objects. keeps one growable buffer and appends into it:
Rules of thumb:
and compare characters case-sensitively and ordinally. For case-insensitive comparison, say so explicitly:
Avoid : it allocates two new strings and depends on culture rules (the Turkish "I" is the classic trap). Use for identifiers, file names and protocol text, and culture-aware comparison () only for text shown to people.
StringBuilderstringToUpperReplaceTrim++=StringBuildera + b + cstring.ConcatStringBuilderstring.Join(", ", items)==string.Equals(a, b)a.ToLower() == b.ToLower()StringComparison.OrdinalIgnoreCaseStringComparison.CurrentCultures.Trim()s.Replace(...)+StringBuilderToLower()StringComparison.OrdinalIgnoreCasestring+=StringBuilderStopwatchToLower()string s = "hello";
s.ToUpper(); // returns a new string; the result is thrown away
Console.WriteLine(s); // hello
s = s.ToUpper(); // keep the result by assigning it
Console.WriteLine(s); // HELLOusing System.Text;
var builder = new StringBuilder();
for (int i = 1; i <= 5; i++)
{
builder.Append(i).Append(',');
}
builder.Length--; // remove the trailing comma
Console.WriteLine(builder.ToString()); // 1,2,3,4,5string name = "Asha";
int items = 3;
Console.WriteLine($"{name} bought {items} items"); // Asha bought 3 items (interpolation)
Console.WriteLine($"Total: {items * 4.5m:F2}"); // Total: 13.50 (format specifier F2)
Console.WriteLine(string.Join(" | ", new[] { "a", "b", "c" })); // a | b | c
string path = @"C:\data\file.txt"; // verbatim string: backslashes are literal
string json = """{ "name": "Asha" }"""; // raw string literal (C# 11): no escaping needed
Console.WriteLine(path); // C:\data\file.txt
Console.WriteLine(json); // { "name": "Asha" }string a = "Apple";
string b = "apple";
Console.WriteLine(a == b); // False
Console.WriteLine(string.Equals(a, b, StringComparison.OrdinalIgnoreCase)); // True
Console.WriteLine(a.Equals(b, StringComparison.Ordinal)); // Falsestring? input = " ";
Console.WriteLine(string.IsNullOrEmpty(input)); // False
Console.WriteLine(string.IsNullOrWhiteSpace(input)); // True
Console.WriteLine(input?.Length); // 3 (the ?. operator avoids a NullReferenceException)