String Interpolation
Build strings by putting values straight into the text with
Novice · C# · Updated
After this lesson you can
- Build a string with interpolation, including format specifiers
- Fill numbered placeholders with string.Format, and show numbers with C, N and P in a chosen culture such as en-US or de-DE
Key takeaways
- Put
$before the opening quote, and C# works out anything in curly braces and puts it into the text, as in.quot;({rank}) {teamName}" - The braces can hold any expression, not only a variable; an expression with
?:needs parentheses around it. - A format specifier after a colon sets how a number looks:
F2for 2 decimal places,N0for thousands separators,Cfor currency andP0for a percentage, which multiplies by 100. - A comma and a width line up columns (positive right-aligns, negative left-aligns), and a doubled brace,
{{or}}, prints a brace. string.Format("{0} scored {1}", teamName, points)fills numbered placeholders in order, and aCultureInfosuch asde-DEpicks a country's way of writing money and numbers.
So far you've built strings by joining pieces with +. It works, but with several values the quotes and plus signs pile up. String interpolation lets you write the text once, with the values in place.
$ and curly braces
Put $ before the opening quote. Then, inside the string, anything in curly braces is worked out and put into the text:
string teamName = "Georgia";
int rank = 1;
int finalScore = 39;
Console.WriteLine("(" + rank + ") " + teamName + ": " + finalScore);
Console.WriteLine( quot;({rank}) {teamName}: {finalScore}");
(1) Georgia: 39
(1) Georgia: 39
Both lines print the same thing, but the second reads like the output it makes. From now on, this course uses interpolation.
The braces can hold any expression, not only a variable:
int wins = 7;
int losses = 3;
Console.WriteLine( quot;Games played: {wins + losses}");
Console.WriteLine( quot;Winning percentage: {wins * 100 / (wins + losses)}%");
Console.WriteLine( quot;Result: {(wins > losses ? "winning record" : "rebuilding")}");
Games played: 10
Winning percentage: 70%
Result: winning record
An expression with ?: inside the braces needs parentheses around it, because : has a special meaning there.
Formatting numbers
After the value, a colon and a format specifier say how it should look:
| Specifier | Means | Example | Result |
|---|---|---|---|
F2 |
2 decimal places | {3.14159:F2} |
3.14 |
N0 |
thousands separators, no decimals | {1234567:N0} |
1,234,567 |
C |
currency | {12.5m:C} |
$12.50 |
P0 |
a percentage, no decimals | {0.75:P0} |
75% |
decimal price = 12.5m;
double average = 24.5678;
int attendance = 92746;
Console.WriteLine( quot;Price: {price:C}");
Console.WriteLine( quot;Average: {average:F2}");
Console.WriteLine( quot;Attendance: {attendance:N0}");
Price: $12.50
Average: 24.57
Attendance: 92,746
C, N0 and P0 follow your computer's region settings: a computer set up for the United States shows dollars and commas, while one set up for Germany shows 12,50 €. The outputs in this lesson come from a computer set up for the United States; Money and numbers for another country: cultures, below, shows how to choose the country yourself.
Percentages: P wants a fraction
The scoreboard shows each team's winning percentage. Georgia won 7 of its 10 games, and 7 out of 10 is the fraction 0.7. You could multiply by 100 and glue on a % sign yourself, but P does both: it multiplies the value by 100 and adds the percent sign.
double winRate = 0.7;
double fieldGoals = 0.375;
Console.WriteLine( quot;Won: {winRate:P0}");
Console.WriteLine( quot;Field goals: {fieldGoals:P1}");
Console.WriteLine( quot;Oops: {70:P0}");
Won: 70%
Field goals: 37.5%
Oops: 7,000%
The number after P is how many decimal places to show: P0 none, P1 one. Give P the fraction, not a number that's already a percentage: 70 becomes 7,000%.
Lining up columns
A comma and a number set a minimum width: positive pads on the left (right-aligns), negative pads on the right (left-aligns). It's handy for tables:
Console.WriteLine( quot;{"Team",-12}{"Final",6}");
Console.WriteLine( quot;{"Georgia",-12}{39,6}");
Console.WriteLine( quot;{"Ohio State",-12}{52,6}");
Team Final
Georgia 39
Ohio State 52
Braces in the text
To print a curly brace itself, double it: {{ prints {, and }} prints }.
string tag = "p";
Console.WriteLine( quot;CSS: {tag} {{ color: navy; }}");
CSS: p { color: navy; }
The older way: composite formatting
Interpolation came to C# in 2015. Code written before then, and plenty written since, builds strings a different way, and you'll meet it in older projects and in code other developers write. It keeps the text as a template with numbered placeholders, and the values come after it:
string teamName = "Georgia";
int finalScore = 39;
Console.WriteLine("{0} scored {1} points.", teamName, finalScore);
string headline = string.Format("{0} won! {0} scored {1}.", teamName, finalScore);
Console.WriteLine(headline);
Georgia scored 39 points.
Georgia won! Georgia scored 39.
This is composite formatting. {0} is read "placeholder zero": it stands for the first value after the template, {1} for the second, and so on, counting from 0 like an array's indexes. The same placeholder can appear more than once, as {0} does in the headline. Console.WriteLine fills the placeholders and prints the line; string.Format fills them and gives the string back, to store or use later.
Everything after a colon works the same as in interpolation: {1:C}, {0:N0}, {0,-12}.
There's a catch that interpolation can't have: the template and the values are separate, so they can disagree. A {2} with only two values after the template compiles, then stops the program with a FormatException when that line runs. That's why this course writes new code with interpolation, and reads composite formatting when it meets it.
Money and numbers for another country: cultures
The stadium starts selling tickets online to fans in Germany, where twelve hundred thirty-four euros and fifty cents is written 1.234,50 €: a period between the thousands, a comma before the cents, and the € sign after the number. Format a price with C on the stadium's server in the United States, and every German fan sees dollars, written the American way.
In .NET, a culture is one country and language's rules for writing numbers, money and dates. Each has a name: a language code, a dash, and a country code, such as en-US (English, United States), en-GB (English, Great Britain) and de-DE (German, Germany). A CultureInfo object holds one culture's rules, and you hand it to ToString or to string.Format:
using System.Globalization;
decimal price = 1234.5m;
CultureInfo unitedStates = new CultureInfo("en-US");
CultureInfo britain = new CultureInfo("en-GB");
CultureInfo germany = new CultureInfo("de-DE");
Console.WriteLine(price.ToString("C", unitedStates));
Console.WriteLine(price.ToString("C", britain));
Console.WriteLine(price.ToString("C", germany));
Console.WriteLine(string.Format(germany, "Total: {0:N2}", price));
$1,234.50
£1,234.50
1.234,50 €
Total: 1.234,50
using System.Globalization;at the top of the file lets you writeCultureInfowithout its long full name.price.ToString("C", germany)formats one value with the format specifier and the culture you choose.string.Format(germany, ...)uses that culture for every placeholder in the template.
Without a culture, C, N and P use the computer's own region settings, so the same code can print $12.50 on one computer and 12,50 € on another. Naming the culture makes the output the same on every computer, which is what you want for a fan in Germany, or for a test that checks the text.
Do it: make a ticket line for the stadium
The stadium's ticket window prints one line for each order: the team, how many tickets, the price of one, and the total. Every amount shows dollars and cents.
The method gets three values:
teamName: the team the tickets are for, astring("Georgia").tickets: how many tickets were bought, anint(3).price: the price of one ticket, adecimal(12.50m).
For example, 3 tickets to Georgia at $12.50 each:
| Part of the line | Comes from | Here |
|---|---|---|
| The team | teamName |
Georgia |
| How many | tickets |
3 |
| The price of one, with 2 decimal places | price |
$12.50 |
| The total, with 2 decimal places | tickets × price |
$37.50 |
So TicketLine("Georgia", 3, 12.50m) returns exactly this text:
Georgia: 3 x $12.50 = $37.50
Your job: write the method TicketLine(string teamName, int tickets, decimal price) so it returns the line, a string, built with interpolation.
- The line is: the team's name, a colon, the number of tickets, the letter
x, the price, an equals sign=, then the total. - Put one space after the colon, and one space on each side of the
xand of the=, exactly as in the example. - A
$sign goes in front of the price and in front of the total. - The price and the total always show 2 decimal places, even for whole dollars: a $45 ticket shows as
$45.00. - 0 tickets is still a line, with a total of
$0.00.
Practiced live on the lesson page: write the C# right there and check it.
Do it: fill in the scoreboard's old message template
The stadium's scoreboard program is older than interpolation. Its end-of-game message is a template with numbered placeholders, and the new message has to be written the same way, with string.Format, so it matches the rest of the program.
The method gets four values:
winner: the team that won, astring("Georgia").loser: the team that lost, astring("Alabama").winnerScore: the winner's points, anint(27).loserScore: the loser's points, anint(24).
For example, Georgia beat Alabama 27 to 24:
| Placeholder | Value | Here |
|---|---|---|
{0} |
winner |
Georgia |
{1} |
loser |
Alabama |
{2} |
winnerScore |
27 |
{3} |
loserScore |
24 |
So FinalMessage("Georgia", "Alabama", 27, 24) returns exactly this text:
Georgia beat Alabama, 27-24. Way to go, Georgia!
Your job: write the method FinalMessage(string winner, string loser, int winnerScore, int loserScore) so it returns the message, a string, built with string.Format and numbered placeholders.
- The message is: the winner, the word
beat, the loser and a comma, then the winner's score, a dash-and the loser's score, then a period. - After that comes one space, then
Way to go,, the winner's name again, and!. - The winner's name appears twice: use the same placeholder for both.
- Spaces and punctuation are exactly as in the example.
Practiced live on the lesson page: write the C# right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Interpolation keeps the shape of the output visible in your code, and format specifiers handle money, decimals and columns without any extra arithmetic. Composite formatting is the older template-and-placeholders way you'll read in existing code, and a culture makes money and numbers look right for the country that reads them.