Strings, Interpolation, Raw Literals & StringBuilder Masterclass
Welcome to Phase 5 (Chapter 11): C# Strings, Verbatim, Raw String Literals & StringBuilder Masterclass! Strings in C# are immutable sequences of UTF-16 Unicode characters. In this chapter, we master string creation, immutability, manipulation methods (ToUpper, ToLower, Trim, Contains, StartsWith, EndsWith, IndexOf, Substring, Replace, Split, Join), string interpolation, verbatim strings (@""), C# 11 Raw String Literals ("""..."""), and high-performance string concatenation using StringBuilder.
Strings in C# are reference types stored on the Heap. They are strictly immutable โ once created, a string object's character sequence cannot be modified. Any method that appears to alter a string (like Replace or ToUpper) actually allocates and returns a brand new string instance in heap memory.
string language = " C# Programming ";
Console.WriteLine($"Original Length: {language.Length}");
Console.WriteLine($"ToUpper(): '{language.ToUpper()}'");
Console.WriteLine($"ToLower(): '{language.ToLower()}'");
Console.WriteLine($"Trim(): '{language.Trim()}'");
Console.WriteLine($"Contains('C#'): {language.Contains("C#")}");
Console.WriteLine($"StartsWith(' C#'): {language.StartsWith(" C#")}");
Console.WriteLine($"EndsWith('ing '): {language.EndsWith("ing ")}");
Console.WriteLine($"IndexOf('Pro'): {language.IndexOf("Pro")}");
Console.WriteLine($"Substring(5, 7): '{language.Trim().Substring(3, 7)}'");
Console.WriteLine($"Replace('C#', 'Modern C#'): '{language.Replace("C#", "Modern C#").Trim()}'");
// String Split and Join
string csvData = "Apple,Banana,Orange,Mango";
string[] fruits = csvData.Split(',');
Console.WriteLine($"Joined with hyphen: {string.Join(" - ", fruits)}");
Trim(): Removes leading and trailing whitespace characters.Split(','): Breaks a string into an array of substrings based on a delimiter character.string.Join(" - ", fruits): Concatenates array elements using a specified separator string.
C# provides specialized string literal formats for file paths, regex patterns, multiline templates, and high-performance loop concatenation:
using System.Text;
// 1. Verbatim String Literal (@) โ disables escape sequences (
, )
string filePath = @"C:UsersBalajiDocumentsProjectProgram.cs";
Console.WriteLine($"File Path: {filePath}");
// 2. C# 11 Raw String Literal (""") โ multiline JSON/XML without escaping double quotes!
string jsonPayload = """
{
"student": {
"name": "Ravi",
"age": 21,
"course": "C# Masterclass"
}
}
""";
Console.WriteLine($"JSON Payload:
{jsonPayload}");
// 3. StringBuilder โ Mutable string object for high-speed string building in loops
StringBuilder sb = new StringBuilder();
sb.AppendLine("=== STUDENT REPORT ===");
for (int i = 1; i <= 3; i++)
{
sb.AppendLine($"Module #{i}: Completed successfully.");
}
Console.WriteLine(sb.ToString());
Why StringBuilder?
Using standard + string concatenation inside a loop creates N temporary string objects on the Heap. StringBuilder allocates a mutable buffer that grows dynamically, performing concatenations in-place with O(1) efficiency.
Q1: Why are strings immutable in C#?
Immutability makes strings inherently thread-safe, enables string interning (reusing identical string literals in memory to save space), and prevents unintended side effects when strings are shared across objects.
Q2: When should I use StringBuilder instead of string concatenation (+)?
Use StringBuilder when performing repeated string modifications or concatenations inside loops. Standard + creates a new heap object on every iteration, pressuring the Garbage Collector.