What is the difference between String and StringBuilder in C#?
Answer
string (alias for System.String) is immutable — every operation that appears to modify a string (concatenation, replace, etc.) actually creates a new string object. Concatenating N strings in a loop creates N intermediate strings, leading to O(n²) memory allocations and GC pressure. StringBuilder is a mutable buffer that grows dynamically, performing in-place modifications — ideal for building strings incrementally. Example: var sb = new StringBuilder(); foreach (var item in items) { sb.Append(item).Append(", "); } string result = sb.ToString();. Use string: for simple concatenation of few strings, for string literals and constants. Use StringBuilder: when concatenating in loops, building strings with many parts, or in performance-critical code. string.Concat() and $"..." interpolation (which uses string.Format) are optimized for a few operands but still create new strings.