Strings, Interpolation & StringBuilder
Text is everywhere — names, messages, file contents, reports. This lesson goes well beyond basic printing: you'll master string interpolation and formatting, the essential string methods for cleaning and searching text, verbatim strings for paths and multi-line text, and StringBuilder for efficiently building large strings.
Learn Strings, Interpolation & StringBuilder in our free C# course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a…
Part of the free C# course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
💡 Real-World Analogy
An immutable string is like a printed photograph . You can't edit the photo itself — if you want a brighter version, you make a new print; the original stays exactly as it was. That's why name.ToUpper() hands you a new string and leaves name alone. A StringBuilder , by contrast, is the editable digital file on your computer: you tweak it as many times as you like in place, and only "print" (call ToString() ) once you're done.
1. Interpolation & Formatting
Interpolation — the $"..." syntax — is the modern way to build text from values. After a colon you can add a format specifier ( :C , :F2 , :P0 ) and after a comma an alignment width for neat columns. It's far more readable than gluing strings together with + .
2. The Essential String Methods
Strings come with a rich toolkit. Trim removes surrounding whitespace, ToUpper / ToLower change case, Replace swaps text, Contains / IndexOf search, and Substring extracts a slice. Split turns text into an array and string.Join glues an array back into text. Remember: every one of these returns a new string — the original never changes.
Your turn. Clean up a messy name and reformat it to proper case. The trickier capitalisation lines are written for you — fill in the Trim blank.
3. StringBuilder for Heavy Lifting
Because strings are immutable, building one with += inside a loop secretly creates a fresh string every iteration — quadratic work that crawls for large inputs. StringBuilder keeps one growable buffer and mutates it with Append and AppendLine , materialising the final string only when you call ToString() . Reach for it whenever you build text in a loop.
🔎 Deep Dive: verbatim & raw strings
A verbatim string @"..." treats backslashes literally — perfect for Windows paths and regex patterns — and lets the text span multiple lines exactly as typed. Prefix with both $@ (or @$ ) to get interpolation and verbatim behaviour together.
Newer C# (11+) also offers raw string literals with triple quotes """...""" , which handle embedded quotes and indentation cleanly — great for JSON or HTML blocks. Verbatim strings remain the workhorse you'll see most often.
🧩 Reorder Challenge
These six lines build a comma-separated list with a StringBuilder and print red, green, blue . Put them in working order.
Why: colours must exist before the loop iterates it, and the StringBuilder must exist before Append is called. The loop fills the buffer, then we trim the trailing ", " into result , and print it last. (The stray sb.ToString() line was a distractor — the real final string is result .)
🧠 Quick Recall
Hello — strings are immutable, so ToUpper() returns a new string that's thrown away. You'd need s = s.ToUpper(); to keep it.
3 — Split('-') breaks the text into ["a", "b", "c"] , an array of length 3.
" 42" — the ,5 right-aligns 42 in a 5-character field, padding with three spaces.
Pro Tips
- 💡 Reassign the result. name = name.Trim(); — string methods don't change the original in place.
- 💡 StringBuilder for loops , plain interpolation for a couple of joins. Match the tool to the size.
- 💡 Compare with StringComparison.OrdinalIgnoreCase instead of lowercasing both sides.
- 💡 Use string.IsNullOrWhiteSpace(s) to check for empty or blank input in one call.
Common Errors (and the fix)
- "Why didn't my string change?" You called s.Replace(...) but ignored the result. Assign it back: s = s.Replace(...); .
- "IndexOutOfRangeException" on Substring : you asked for more characters than the string has. Check Length first.
- Slow concatenation: building a big string with += in a loop is quadratic. Switch to StringBuilder .
- Case-sensitive comparison surprise: "Yes" == "yes" is false . Use OrdinalIgnoreCase when case shouldn't matter.
Frequently Asked Questions
Mini-Challenge: Build an Invoice
Use a StringBuilder to assemble a multi-line invoice, formatting each price as currency and summing a total. The outline is in the comments.
🎉 Lesson Complete
- ✅ Interpolation $"..." with :C , :F2 formats and ,width alignment
- ✅ Core methods: Trim , ToUpper , Replace , Contains , Substring , Split , Join
- ✅ Strings are immutable — methods return a new string, so reassign the result
- ✅ Verbatim @"..." for paths and multi-line text; $@ combines both
- ✅ StringBuilder efficiently builds large strings in loops
- ✅ Next lesson: List<T> — store and manage ordered collections
Practice quiz
Why are C# strings immutable?
- They can be changed in place
- They are always empty
- Once created, their characters never change; methods return new strings
- They store numbers only
Answer: Once created, their characters never change; methods return new strings. Immutable means a string's contents never change; methods like ToUpper return a brand-new string.
What does s.ToUpper() do if you don't assign its result back to s?
- Returns a new string that is discarded, leaving s unchanged
- Changes s in place
- Throws an error
- Empties s
Answer: Returns a new string that is discarded, leaving s unchanged. Strings are immutable, so ToUpper returns a new string; without s = s.ToUpper(); the original is unchanged.
What is the length of the array from "a-b-c".Split('-') ?
- 1
- 2
- 4
- 3
Answer: 3. Split('-') breaks the text into ["a", "b", "c"], an array of length 3.
Which class is best for building a large string in a loop?
- String
- StringBuilder
- List
- Array
Answer: StringBuilder. StringBuilder mutates one internal buffer (O(n)), avoiding the quadratic cost of += in a loop.
What does string.Join(" | ", parts) do?
- Glues array elements together with a separator
- Splits text into parts
- Trims whitespace
- Reverses the string
Answer: Glues array elements together with a separator. Join combines the elements of an array into one string, separated by the given text.
What does a verbatim string @"C:\Reports" treat backslashes as?
- Escape characters
- New lines
- Literal characters
- Errors
Answer: Literal characters. In a @"..." verbatim string, backslashes are literal — no escaping needed, ideal for file paths.
Which method removes whitespace from both ends of a string?
- Replace
- Trim
- Substring
- Split
Answer: Trim. Trim() returns a new string with surrounding whitespace removed.
What does "Yes" == "yes" evaluate to?
- true
- an error
- null
- false
Answer: false. String comparison with == is case-sensitive by default, so "Yes" and "yes" are not equal.
What does the alignment in $"{42,5}" produce?
- "42 "
- " 42"
- "42"
- "00042"
Answer: " 42". A positive width right-aligns the value in a field of that width, padding the left with spaces: " 42".
When is StringBuilder unnecessary?
- When looping thousands of times
- Never use plain strings
- For just a couple of joins
- Only with numbers
Answer: For just a couple of joins. For a handful of concatenations, plain + or interpolation is fine and more readable; reach for StringBuilder in loops.
Continue this course
- Previous: User Input (Console.ReadLine)
- Next: List<T>