C#
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented C#
-
Section 4: Working with Data
-
Section 5: Error Handling
-
Section 6: Delegates and Events
-
Section 7: Async Programming
-
Section 8: More Language Features
-
Section 9: File I/O and Serialization
-
Section 10: Networking in .NET
-
Section 11: The .NET Ecosystem
-
Section 12: Memory and Performance
-
Section 13: Concurrency Beyond Async
-
Section 14: Reflection and Attributes
-
Section 15: Testing and Best Practices
-
Section 16: Design Patterns in C#
-
Section 17: Standard Library Deep Dive
-
Section 18: Data Structures and Algorithms in C#
-
Section 19: GUI and Desktop Development Overview
-
Section 20: Practical Projects
-
Section 21: More Practice Exercises
-
Section 22: More Standard Library and Text Processing
-
Section 23: More Design Patterns
-
Section 24: More Projects
-
Section 25: Interview Practice
-
Section 26: C# Keywords Reference (Modifiers)
-
Section 27: C# Keywords Reference (Statements)
-
Section 28: C# Keywords Reference (Operators)
-
Section 29: BCL: System.Collections.Generic
-
Section 30: BCL: System.Linq
-
Section 31: BCL: System.Threading
-
Section 32: BCL: System.IO
-
Section 33: BCL: System.Text and System.Text.Json
-
Section 34: BCL: System.Net.Http
-
Section 35: C# Language Specification Topics
-
Section 36: More Practice Exercises
-
Section 37: More Async Patterns
-
Section 38: More BCL: System.Reflection and System.Diagnostics
-
Section 39: Nullable Reference Types In Depth
-
Section 40: C# Records and Pattern Matching In Depth
-
Section 41: Dependency Injection Deep Dive
-
Section 42: More Interview and Whiteboard Practice
16: String Interpolation and Formatting
When you first start putting variables into strings, your instinct is probably to just use the + operator. It feels natural—you're just adding pieces of text together. But once you start building something more complex, like a player statistics summary for a game, that approach turns into a nightmare of quotation marks and missing spaces.
The Mess of Plus Signs
Imagine you're building a summary for a character sheet. You have a name, a level, an amount of gold, and a win rate. If you do this the naive way, it looks like this:
string summary = "Player: " + playerName + " | Level: " + level + " | Gold: " + gold + " | Win Rate: " + winRate + "%";
I've spent way too many hours of my career debugging "glued together" words because I forgot to put a space inside one of those quotes. It's visually noisy, and it's surprisingly easy to lose track of where you are in the string. Beyond the aesthetics, this is also inefficient. Every time you use + with strings in a tight loop, you're essentially creating new string objects in memory because strings in C# are immutable. For a single line, it doesn't matter, but it's a bad habit to bake into your brain.
The Indexing Headache of string.Format
For a long time, the "professional" way to handle this was string.Format(). It separates the template from the data, which is a huge step up in readability:
string summary = string.Format("Player: {0} | Level: {1} | Gold: {2} | Win Rate: {3}%", playerName, level, gold, winRate);
This is better, but it introduces a new problem: index tracking. If you decide to add "Class" to the middle of that string, you have to manually re-number every single index that follows it. If you accidentally put {4} in a string that only has four arguments, the program crashes with a FormatException. I can't tell you how many times I've seen a production log filled with these errors just because someone moved a variable in a sentence.
The Elegance of the Dollar Sign
This is why we use String Interpolation. By putting a $ before the opening quote, you tell C# that this string can contain expressions inside curly braces. It's essentially syntactic sugar for string.Format, but it's written in a way that makes sense to humans:
string summary = $"Player: {playerName} | Level: {level} | Gold: {gold} | Win Rate: {winRate}%";
Now, the variable is exactly where it appears in the text. No counting indices, no messy plus signs, and the compiler checks that your variables actually exist at compile time, not at runtime. It's cleaner, safer, and honestly, just more pleasant to read.
Controlling the Chaos of Decimals and Currency
But interpolation isn't just about plugging in variables; it's about formatting them. If your winRate is 0.754321, you don't want to show the player six decimal places. You can add a colon inside the braces to specify a format string.
For numbers, :F2 fixes the precision to two decimal places. For money, :C automatically detects the user's system locale and adds the correct currency symbol (like $ or €).
decimal goldAmount = 1250.50m;
double winRate = 0.754321;
// "Gold: $1,250.50 | Win Rate: 75.43%"
string detailedSummary = $"Gold: {goldAmount:C} | Win Rate: {winRate:P2}";
I particularly love the :P format for percentages; it multiplies the value by 100 and adds the percent sign automatically. It keeps your logic out of the string and lets the formatting engine handle the presentation. It's a small detail, but it's what separates a "hobbyist" looking UI from a professional one.
📋 Practical Task
Build a Digital Receipt Generator
Create a small program that simulates a retail receipt. You should have the following variables: string itemName, int quantity, decimal unitPrice, and DateTime transactionDate.
- Use string interpolation to create a single summary string.
- The output must format the
unitPriceas currency (:C). - The output must format the
transactionDateto show only the short date (use:d). - The final string should look something like:
"Item: Coffee Beans | Qty: 2 | Price: $15.00 | Date: 10/24/2023".
There are no comments for now.