Reading — step 1 of 6
Learn
String Interpolation
Programs constantly build strings out of pieces: names, quantities, prices. C# has three ways to do it, and knowing why the newest one won makes you faster at reading everyone else's code too.
1. Concatenation — gluing with +:
string s = "Hello, " + name + "!";
Works, but gets noisy fast, and it is easy to lose a space between pieces.
2. string.Format — printf-style positional placeholders:
string s = string.Format("{0} is {1} years old", name, age);
You have to count positions and match them to arguments by hand — a classic source of mixed-up output.
3. Interpolation — the modern idiom (C# 6+). Prefix the string with $ and put expressions directly inside braces:
string s = $"{name} is {age} years old";
Each expression sits exactly where its output will appear. The compiler checks that name and age actually exist — typos become compile errors instead of garbled output. This is the style to reach for by default.
Format specifiers — controlling how numbers print
Inside the braces, add a colon and a format code:
double total = 1.5;
Console.WriteLine($"{total:F2}"); // 1.50 — fixed-point, two decimals
Console.WriteLine($"{total}"); // 1.5 — default formatting
F2 means "fixed-point with exactly two digits after the decimal point": it pads 1.5 to 1.50 and rounds 19.983 down to 19.98. Any time a spec says "two decimals" — receipts, invoices, this lesson's grader — :F2 is the tool.
Also useful: verbatim strings @"C:\Users\Ada" treat backslashes literally (no escape sequences), which is handy for Windows paths and regex. $@"..." combines verbatim with interpolation.
The idiom and the trap
// Idiom: compute first, then format with F2; literal $ goes before the brace
double total = qty * price;
Console.WriteLine($"{name} x {qty} = ${total:F2}");
// Trap 1: forgetting the $ prefix — the braces print literally
Console.WriteLine("{name} x {qty}"); // output: {name} x {qty}
// Trap 2: no :F2 — 1.5 prints as "1.5" but the grader expects "1.50"
Console.WriteLine($"= ${qty * price}");
Note the two dollar signs doing different jobs in the idiom: the $ before the opening quote switches interpolation on; the $ inside the string is just a literal character that gets printed.
Your exercise
Read three lines — a product name, a quantity (int), and a price (double); the starter parses all three. Compute the total (qty * price) and print one receipt line in exactly this shape:
apple x 3 = $1.50
Single spaces around x and =, a literal $ immediately before the total, and the total formatted with :F2. The grader will catch the exact traps above: $1.5 instead of $1.50 (missing :F2), a missing $, or apple x3 (missing space). For book, 2, 9.99 it expects book x 2 = $19.98 — multiply first, then format the product.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…