Strings
In C#, string is a reference type but behaves like a value type because it is immutable — every modification creates a new string object.
Common String Methods
string text = " Hello, World! ";
text.Trim(); // "Hello, World!"
text.ToUpper(); // " HELLO, WORLD! "
text.ToLower(); // " hello, world! "
text.Contains("World"); // true
text.StartsWith(" H"); // true
text.Replace("World", "C#"); // " Hello, C#! "
text.Substring(7, 5); // "World"
string csv = "a,b,c,d";
string[] parts = csv.Split(','); // ["a","b","c","d"]
string joined = string.Join(" | ", parts); // "a | b | c | d"
String Interpolation
The $ prefix lets you embed expressions directly:
string name = "Andi";
int age = 30;
Console.WriteLine($"Name: {name}, Age: {age}");
Console.WriteLine($"Next year: {age + 1}");
Console.WriteLine($"Upper: {name.ToUpper()}");
StringBuilder for Performance
Strings are immutable, so concatenation in a loop creates many temporary objects. Use StringBuilder instead:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append($"Line {i}\n");
}
string result = sb.ToString();
Rule of thumb: Use string for small operations and StringBuilder when building strings in loops or with many concatenations.
Verbatim & Raw Strings
// Verbatim string — no escape sequences
string path = @"C:\Users\andi\file.txt";
// Raw string literal (C# 11+)
string json = \"\"\"
{
"name": "Andi",
"age": 30
}
\"\"\";