Everything about strings
Strings are everywhere: user input, emails, coupons, JSON. In C# a string is immutable, so every method returns a new string; knowing that, plus interpolation, comparison rules and StringBuilder, avoids the most common string bugs.
8.1 Problem: Trim() called, coupon still rejected
C#
string coupon = " diwali50 "; coupon.Trim();coupon.ToUpper(); Console.WriteLine(coupon == "DIWALI50");Console.WriteLine($"[{coupon}]");Output
$ dotnet run Coupon.csFalse[ diwali50 ]- Step 1
1.coupon points to " diwali50 "
- Step 2
2.coupon.Trim() builds a NEW string "diwali50"
- Step 3
3.The new string is not stored anywhere, so it is lost
- Step 4
4.Same for ToUpper(): another new string, also lost
- Step 5
5.coupon still points to the original " diwali50 "
Strings are immutable: methods return a new string
8.2 Fix: assign the result
C#
string coupon = " diwali50 "; coupon = coupon.Trim().ToUpper(); Console.WriteLine(coupon == "DIWALI50");Console.WriteLine($"[{coupon}]");Output
$ dotnet run Coupon.csTrue[DIWALI50]8.3 String interpolation + format
- $"..." lets you put any expression inside { }.
- {value:F2}: two decimal places; {date:dd-MM-yyyy}: date pattern.
- {value,-6}: width 6, left-aligned; {value,4}: width 4, right-aligned.
C#
string name = "Asha";int qty = 3;decimal price = 499.5m;DateTime date = new(2026, 11, 6); Console.WriteLine($"Hi {name}, {qty} items");Console.WriteLine($"Total: {qty * price:F2}");Console.WriteLine($"Date: {date:dd-MM-yyyy}");Console.WriteLine($"|{"Pen",-6}|{qty,4}|");Output
$ dotnet run Bill.csHi Asha, 3 itemsTotal: 1498.50Date: 06-11-2026|Pen | 3|8.4 Common string methods
C#
string email = "Rahul.Sharma@Gmail.com"; int at = email.IndexOf('@');string user = email.Substring(0, at);string domain = email.Substring(at + 1); Console.WriteLine(user);Console.WriteLine(domain.ToLower());Console.WriteLine(email.Contains("gmail"));Console.WriteLine(email.EndsWith(".com")); string[] parts = user.Split('.');Console.WriteLine(string.Join(" ", parts));Console.WriteLine(user.Replace(".", "_"));Output
$ dotnet run Email.csRahul.Sharmagmail.comFalseTrueRahul SharmaRahul_Sharma| Method | What it does | Example result |
|---|---|---|
| IndexOf('@') | Position of a character (-1 if missing) | 12 |
| Substring(start, length) | Part of the string | Rahul.Sharma |
| Contains / StartsWith / EndsWith | Search; case-sensitive by default | Contains("gmail") = False |
| Split('.') | Breaks into a string[] | ["Rahul", "Sharma"] |
| string.Join(" ", parts) | Combines parts with a separator | Rahul Sharma |
| Replace(".", "_") | Swaps text | Rahul_Sharma |
| Trim / ToUpper / ToLower | Clean-up / case change (new string) | DIWALI50 |
8.5 How to compare strings
- == compares content and is case-sensitive: "Admin" == "admin" is False.
- To ignore case: Equals(other, StringComparison.OrdinalIgnoreCase).
- Two separate objects with the same text: == is True, ReferenceEquals is False.
C#
string role = "Admin";string typed = "admin";string copy = typed.Replace('a', 'A'); Console.WriteLine(role == typed);Console.WriteLine(role.Equals(typed, StringComparison.OrdinalIgnoreCase));Console.WriteLine(role == copy);Console.WriteLine(ReferenceEquals(role, copy));Output
$ dotnet run Compare.csFalseTrueTrueFalse8.6 StringBuilder: text in a loop
- s += "x" in a loop copies the whole string every round: 50,000 rounds = 50,000 strings.
- StringBuilder keeps a mutable buffer; Append adds at the end, ToString builds the final string once.
C#
using System.Diagnostics;using System.Text; int n = 50_000;var sw = Stopwatch.StartNew();string s = "";for (int i = 0; i < n; i++) s += "x";long concat = sw.ElapsedMilliseconds;sw.Restart();var sb = new StringBuilder();for (int i = 0; i < n; i++) sb.Append('x');string t = sb.ToString();long builder = sw.ElapsedMilliseconds;Console.WriteLine($"Concat: {concat} ms");Console.WriteLine($"Builder: {builder} ms");Output
$ dotnet run Builder.csConcat: 366 msBuilder: 0 ms8.7 Raw string literals and verbatim strings
- Raw strings (C# 11): start with """, no escaping for quotes inside, indentation up to the closing quotes is removed.
- $$""" means interpolation uses {{ }}, so single { } stay normal JSON characters.
- Verbatim @"...": backslashes are not escapes; handy for Windows paths.
C#
string name = "Asha";int id = 42; string json = $$""" { "id": {{id}}, "name": "{{name}}" } """;Console.WriteLine(json); string path = @"C:\bills\nov.txt";Console.WriteLine(path);Output
$ dotnet run Raw.cs{ "id": 42, "name": "Asha"}C:\bills\nov.txt8.8 Checkpoint: immutability
C#
string a = "Hello";string b = a;a += " World";a.ToUpper();Console.WriteLine(a);Console.WriteLine(b);Output
$ dotnet run Quiz.csHello WorldHello- += built a new string for a; b still points to the original "Hello".
- The ToUpper() result was never assigned, so it was ignored.
8.9 Common mistakes
- Calling Trim/ToUpper/Replace without assigning the result.
- Comparing with ToLower(): creates an extra string every time and depends on culture (Turkish 'I' has a different lowercase). Use Equals with OrdinalIgnoreCase.
- Myth (from Java): == compares references. In C#, == compares string content.
- Myth: every + is slow. Joining 2-3 strings in one line is fine; StringBuilder is for loops and many appends.
C#
string answer = "YES"; if (answer.Equals("yes", StringComparison.OrdinalIgnoreCase)) Console.WriteLine("Order confirmed");8.10 Interview tips
- Strings are immutable, so they are thread-safe to share and safe as dictionary keys.
- Interning: literals with the same text reuse one object.
- Cost of immutability: every change makes a new string, so use StringBuilder for many appends in a loop.
- Always pass StringComparison explicitly when comparing.
- == on strings compares content, not references.