Skip to content
Lesson 3 of 12

Step 1 of 6 · Reading · ~3 min

Learn

Basics

String Interpolation

By the end of this lesson you can build output lines from variables with $"...", control how many decimals a number shows, and line values up in columns.

Programs constantly build strings out of pieces. C# has three ways to do it:

string a = "Hello, " + name + "!";                    // 1. concatenation
string b = string.Format("{0} is {1} years old", name, age);   // 2. positional placeholders
string c = $"{name} is {age} years old";              // 3. interpolation

Concatenation gets noisy and it is easy to lose a space. string.Format makes you count positions. Interpolation (the $ before the opening quote) puts each expression exactly where its output will appear, and the compiler checks that the names exist. Reach for it by default. Anything valid as an expression can sit inside the braces: {price * 2} or {age + 1}.

Format specifiers

After the expression, a colon and a code control how a number prints. F2 means fixed-point with exactly two digits after the point; F0 means none:

double temp = -3.456;
int steps = 12000;
Console.WriteLine($"{temp:F1}");   // -3.5   (rounded to one decimal)
Console.WriteLine($"{temp}");      // -3.456 (default: whatever digits it has)
Console.WriteLine($"{2.0:F2}");    // 2.00   (padded with zeros)
Console.WriteLine($"{steps:N0}");  // 12,000 (thousands separators)

Without a format, a double prints its shortest form, so a total like 1.5 shows as 1.5, not 1.50. Anywhere a spec says "two decimals", use :F2. The code rounds; it does not truncate.

Alignment

A comma and a width, placed before the colon, pad the value to at least that many characters. A positive width right-aligns, a negative width left-aligns:

string city = "Oslo";
Console.WriteLine($"[{city,-8}]");       // [Oslo    ]
Console.WriteLine($"[{temp,7:F1}]");     // [   -3.5]
string longCity = "Johannesburg";
Console.WriteLine($"[{longCity,-8}]");   // [Johannesburg]

The order is always expression, then ,width, then :format. The last line shows that a width is a minimum: a longer value is never cut off, so it pushes the columns after it to the right. Use alignment to make columns line up in tables and reports.

Literal characters

A $ inside the string is just a character, so $"cost: ${total:F2}" prints a dollar sign followed by the number: the first $ switches interpolation on, the one inside the quotes is printed. To print an actual brace, double it: $"{{{count}}}" prints {4} when count is 4. A verbatim string @"C:\temp" treats backslashes literally, and $@"..." combines both.

Common mistakes

  • Forgetting the $ prefix. "{name} scored {pts}" prints the braces and the names literally.
  • Leaving out :F2. A total of 1.5 prints 1.5; a specification of two decimals wants 1.50.
  • Putting the format before the width. {x:F2,8} is not alignment; write {x,8:F2}.
  • Counting alignment as a maximum. A width of 6 does not shorten a 9-character value; it only pads shorter ones.

Your exercise

The starter reads a product name, a quantity and a unit price. Print one line with the name, quantity and total in aligned columns, exactly as the exercise shows. The most likely mistake is mixing up left and right alignment, or forgetting that the total needs two decimals.

Up nextIf/Else and SwitchControl Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…