Bird
Raised Fist0
C Sharp (C#)programming~10 mins

String interpolation and formatting in C Sharp (C#) - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - String interpolation and formatting
Start
Define variables
Create interpolated string
Apply formatting if needed
Output final string
End
This flow shows how variables are inserted into strings using interpolation and formatting, then output.
Execution Sample
C Sharp (C#)
int age = 25;
string name = "Alice";
string message = $"Name: {name}, Age: {age:D3}";
Console.WriteLine(message);
This code creates a message string with name and age, formatting age as a 3-digit number with leading zeros.
Execution Table
StepActionVariable ValuesString CreatedOutput
1Define ageage=25
2Define namename="Alice"
3Create interpolated stringage=25, name="Alice"Name: Alice, Age: 025
4Print stringage=25, name="Alice"Name: Alice, Age: 025Name: Alice, Age: 025
💡 All steps completed, string printed with formatted age.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
ageundefined25252525
nameundefinedundefined"Alice""Alice""Alice"
messageundefinedundefinedundefined"Name: Alice, Age: 025""Name: Alice, Age: 025"
Key Moments - 2 Insights
Why does the age show as 025 instead of 25?
Because the format specifier :D3 tells C# to format the number with at least 3 digits, adding leading zeros if needed, as shown in step 3 of the execution_table.
What does the $ symbol before the string mean?
The $ symbol marks the string as interpolated, allowing variables inside { } to be replaced with their values, as seen in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'message' after step 3?
A"Name: Alice, Age: 025"
B"Name: Alice, Age: 25"
C"Name: {name}, Age: {age:D3}"
D"Name: Alice, Age: 250"
💡 Hint
Check the 'String Created' column at step 3 in the execution_table.
At which step is the interpolated string actually printed to the console?
AStep 1
BStep 4
CStep 2
DStep 3
💡 Hint
Look at the 'Output' column in the execution_table.
If we remove ':D3' from the interpolation, how would the output change?
AThe code would cause an error
BAge would print as 025
CAge would print as 25 without leading zeros
DName would not print
💡 Hint
Refer to the formatting effect explained in key_moments and step 3 of execution_table.
Concept Snapshot
String interpolation in C# uses $ before a string.
Variables inside { } are replaced with their values.
Format specifiers like :D3 format numbers (3 digits, leading zeros).
Example: $"Age: {age:D3}" outputs Age: 025 if age=25.
Use Console.WriteLine() to print the final string.
Full Transcript
This example shows how to use string interpolation and formatting in C#. First, variables age and name are defined. Then, an interpolated string is created using $ and curly braces to insert variable values. The age variable is formatted with :D3 to show three digits with leading zeros. Finally, the string is printed to the console. The execution table traces each step, showing variable values and the string created. Key moments clarify why formatting changes the output and the role of the $ symbol. The visual quiz tests understanding of these steps and effects.

Practice

(1/5)
1. What does the following C# code do?
int age = 25;
string message = $"I am {age} years old.";
easy
A. Concatenates the string and integer without formatting.
B. Inserts the value of age into the string at the placeholder.
C. Causes a syntax error because of the dollar sign.
D. Creates a string with the text including curly braces literally.

Solution

  1. Step 1: Understand string interpolation syntax

    The dollar sign $ before the string allows inserting variables inside curly braces.
  2. Step 2: Identify variable insertion

    The variable age is inserted where {age} appears, replacing the placeholder with its value.
  3. Final Answer:

    Inserts the value of age into the string at the placeholder. -> Option B
  4. Quick Check:

    String interpolation = Insert variable value [OK]
Hint: Look for $ and {variable} to spot interpolation [OK]
Common Mistakes:
  • Thinking $ means string concatenation
  • Expecting curly braces to print literally
  • Confusing interpolation with format method
2. Which of the following is the correct syntax for formatting a double value to show two decimal places using string interpolation in C#?
easy
A. double price = 9.99; string s = $"Price: {price:0.00}";
B. double price = 9.99; string s = $"Price: {price,2}";
C. double price = 9.99; string s = $"Price: {price:.2f}";
D. double price = 9.99; string s = $"Price: {price.ToString("0.00")}";

Solution

  1. Step 1: Recognize C# format specifier syntax

    In C#, inside interpolation braces, :0.00 formats numbers to two decimals.
  2. Step 2: Check each option's correctness

    double price = 9.99; string s = $"Price: {price:0.00}"; uses correct format {price:0.00}. double price = 9.99; string s = $"Price: {price,2}"; uses comma which is for alignment, not decimals. double price = 9.99; string s = $"Price: {price:.2f}"; uses Python style .2f which is invalid in C#. double price = 9.99; string s = $"Price: {price.ToString("0.00")}"; calls ToString inside interpolation but with escaped quotes incorrectly.
  3. Final Answer:

    double price = 9.99; string s = $"Price: {price:0.00}"; -> Option A
  4. Quick Check:

    Format decimals with :0.00 inside {} [OK]
Hint: Use colon and format code inside braces for formatting [OK]
Common Mistakes:
  • Using Python or other language format codes
  • Confusing alignment comma with format colon
  • Trying to call methods inside interpolation incorrectly
3. What is the output of the following code?
int x = 5;
int y = 3;
string result = $"Sum: {x + y}, Product: {x * y}";
Console.WriteLine(result);
medium
A. Sum: 53, Product: 15
B. Sum: {x + y}, Product: {x * y}
C. Sum: 8, Product: 15
D. Sum: 8 Product: 15

Solution

  1. Step 1: Evaluate expressions inside interpolation

    The expressions {x + y} and {x * y} calculate 5 + 3 = 8 and 5 * 3 = 15 respectively.
  2. Step 2: Check output formatting

    The string inserts these values with a comma and space exactly as written, so output is "Sum: 8, Product: 15".
  3. Final Answer:

    Sum: 8, Product: 15 -> Option C
  4. Quick Check:

    Expressions inside {} are evaluated before output [OK]
Hint: Calculate expressions inside {} before output [OK]
Common Mistakes:
  • Thinking expressions print literally
  • Concatenating numbers as strings
  • Missing commas or spaces in output
4. Identify the error in this C# code snippet:
int count = 10;
string message = $"Count is {count,2.0}";
Console.WriteLine(message);
medium
A. Variable count is not declared.
B. Missing dollar sign for string interpolation.
C. No error; code runs fine.
D. Incorrect format specifier; cannot combine alignment and decimal format like that.

Solution

  1. Step 1: Understand alignment and format syntax

    In interpolation, {variable,alignment:format} is correct. Here, {count,2.0} mixes alignment and format incorrectly without colon.
  2. Step 2: Identify correct syntax

    It should be {count,2:0} or similar. The dot without colon causes syntax error.
  3. Final Answer:

    Incorrect format specifier; cannot combine alignment and decimal format like that. -> Option D
  4. Quick Check:

    Use comma for alignment, colon for format separately [OK]
Hint: Use comma for alignment, colon for format inside {} [OK]
Common Mistakes:
  • Mixing alignment and format without colon
  • Forgetting dollar sign for interpolation
  • Assuming no error when syntax is wrong
5. You want to display a date in the format "Year: 2024, Month: 06, Day: 15" using string interpolation. Which code snippet correctly formats the DateTime object date to achieve this?
hard
A. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date:yyyy}, Month: {date:MM}, Day: {date:dd}";
B. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date.Year}, Month: {date.Month}, Day: {date.Day}";
C. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date:Year}, Month: {date:Month}, Day: {date:Day}";
D. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date.ToString("yyyy")}, Month: {date.ToString("MM")}, Day: {date.ToString("dd")}";

Solution

  1. Step 1: Understand date format strings in interpolation

    Inside interpolation, {date:format} applies the format string to the DateTime object.
  2. Step 2: Compare options

    DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date:yyyy}, Month: {date:MM}, Day: {date:dd}"; uses correct format codes yyyy, MM, dd inside interpolation. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date.Year}, Month: {date.Month}, Day: {date.Day}"; uses properties but month/day will not have leading zeros. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date:Year}, Month: {date:Month}, Day: {date:Day}"; uses invalid format names. DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date.ToString("yyyy")}, Month: {date.ToString("MM")}, Day: {date.ToString("dd")}"; calls ToString with escaped quotes incorrectly.
  3. Final Answer:

    DateTime date = new DateTime(2024, 6, 15); string s = $"Year: {date:yyyy}, Month: {date:MM}, Day: {date:dd}"; -> Option A
  4. Quick Check:

    Use :format inside {} for DateTime formatting [OK]
Hint: Use :yyyy, :MM, :dd inside {} for date formatting [OK]
Common Mistakes:
  • Using property names as format strings
  • Forgetting leading zeros for month/day
  • Overusing ToString inside interpolation unnecessarily