Strings are the most used type in almost every C# application. While they may seem simple, they hold deep architectural secrets: they are Reference Types that behave like Value Types, and they are Immutable, meaning once created, they can never be changed.
When you "change" a string, you aren't actually changing it. C# destroys the old string and creates a brand-new memory object on the heap.
string s = "Hello";
s += " World"; // Physically creates a NEW string "Hello World" in RAM!
+=. Use StringBuilder. StringBuilder creates a mutable buffer in memory that doesn't generate 10,000 garbage objects, saving your CPU from Garbage Collection paralysis.
Modern C# provides beautiful syntax to handle complex strings without messy concatenation.
// 1. String Interpolation ($)
var age = 25;
string msg = $"You are {age} years old.";
// 2. Verbatim Strings (@)
// Great for File Paths and Multiline strings. It ignores escape characters like '\'.
string path = @"C:\Users\Sandeep\Documents";
// 3. Raw String Literals (""") (C# 11+)
// The ultimate way to store JSON or SQL without escaping anything.
string json = """
{
"name": "Sandeep",
"role": "Architect"
}
""";
The CLR maintains a "String Intern Pool." If you have two variables equal to the exact same literal string, C# is smart enough to point both variables to the same memory address to save space.
Q: "Why is a string a Reference Type but behaves like a Value Type when used with the '==' operator?"
Architect Answer: "This is by design for developer experience. By default, reference types (`class`) use 'Reference Equality' (check if the memory addresses match). However, the `string` class has 'Operator Overloading' for the `==` and `!= ` operators to perform 'Value-based Equality' (check if the character sequences match). If you truly need to check if two strings are the exact same memory instance, you must use `Object.ReferenceEquals(s1, s2)`."