CodeGym /Courses /C# SELF /Advanced String Interpolation

Advanced String Interpolation

C# SELF
Level 9, Lesson 2
Available

1. Remembering String Interpolation

Pretty often, we need not just to print a string, but to insert variable values into it. Back in the day, we used either concatenation (+) or the string.Format method for that. But ever since the magic of string interpolation showed up in C#, life got a whole lot better.

How String Interpolation Works

Add a $ before the string, and inside the string use curly braces {} to insert variables or even whole expressions.

Comparing the old and new style of output with variables

string name = "Anna";
int age = 24;

Console.WriteLine("My name is " + name + ", I'm " + age + " years old."); // Old style
Console.WriteLine($"My name is {name}, I'm {age} years old."); // New style!

You can insert calculations and expressions right in there:


int a = 5, b = 10;
Console.WriteLine($"Sum {a} + {b} = {a + b}");

2. How String Interpolation Works

Put a $ before the string, and wrap variables or expressions in curly braces {}:


string name = "Anna";
int age = 24;

Console.WriteLine($"My name is {name}, I'm {age} years old.");
  • Everything outside the braces is just text.
  • Everything inside the braces is interpreted as C# code: it can be a variable name, arithmetic, a method call, etc.

Calculations and Expressions Right in the String

Interpolation isn't just for simple variables! Here's what you can do:

Arithmetic expressions
int apples = 7;
int pears = 5;
Console.WriteLine($"I have {apples + pears} fruits in total."); // 12
String operations and methods
string city = "Budapest";
Console.WriteLine($"City in uppercase: {city.ToUpper()}"); // BUDAPEST
Ternary operators, conditions
int score = 90;
Console.WriteLine($"Grade: {(score >= 60 ? "pass" : "fail")}");
Method calls
string FormatUser(string name, int age) => $"{name} ({age})";
Console.WriteLine($"User: {FormatUser("Eva", 19)}"); // User: Eva (19)
Working with arrays and collections
int[] numbers = { 3, 5, 7 };
Console.WriteLine($"Sum: {numbers.Sum()}");
Console.WriteLine($"Elements: {string.Join(", ", numbers)}");
Nested expressions and complex constructs
var user = new { Name = "Oleg", Role = "Admin" };
Console.WriteLine($"Name: {user.Name}, role: {(user.Role == "Admin" ? "administrator" : "user")}");
Heads up:

expressions inside the braces should be short and readable. If the logic is complicated, it's better to calculate it beforehand and just insert the ready variable.

Multi-level expressions
var student = new { Name = "Sasha", Info = new { Age = 21, Uni = "Harvard" } };
Console.WriteLine($"Name: {student.Name}, university: {student.Info.Uni}");
On-the-fly type conversions
double price = 19.99;
int count = 3;
Console.WriteLine($"Total cost: {price * count} euro");
Date and time — right in the format you want
DateTime now = DateTime.Now;
Console.WriteLine($"Today: {now.Day}.{now.Month}.{now.Year}");
Example with a loop
var days = new[] { "Mon", "Tue", "Wed" };
Console.WriteLine($"Days of the week: {string.Join(", ", days)}");

3. Formatting Inside Interpolation

It's often important to display numbers, dates, currency, or percentages nicely.
Interpolation lets you specify the format right inside the braces — after a colon.

General syntax: {expression:format}

Number formatting

double num = 1234.5678;
Console.WriteLine($"Rounded: {num:F2}");     // 1234.57
Console.WriteLine($"Exponential form: {num:E1}"); // 1.2E+003
Console.WriteLine($"With digit grouping: {num:N}"); // 1,234.57 (depends on culture)

Format examples:

  • F2 — two decimal places
  • N0 — thousands separator, 0 decimal places
  • E1 — exponential, 1 digit after the dot
  • P0 — percent, 0 digits after the dot
double ratio = 0.1234;
Console.WriteLine($"Percent: {ratio:P1}"); // 12.3 %

Date formatting

DateTime d = new DateTime(2025, 6, 18, 15, 42, 0);
Console.WriteLine($"Date: {d:dd.MM.yyyy}");         // 18.06.2025
Console.WriteLine($"Time: {d:HH:mm}");             // 15:42
Console.WriteLine($"ISO: {d:yyyy-MM-ddTHH:mm:ss}"); // 2025-06-18T15:42:00

Quick date format guide:

  • dd — day (2 digits)
  • MM — month
  • yyyy — year
  • HH:mm — hours:minutes (24-hour)
  • d — short date by culture
  • D — long date

Currency and money formatting

decimal cost = 2999.5m;
Console.WriteLine($"Price: {cost:C}"); // $2,999.50  (depends on culture)

Alignment and padding

You can set the field width, align to the right or left:

int val = 7;
Console.WriteLine($"[{val,5}]");  // [    7] — right
Console.WriteLine($"[{val,-5}]"); // [7    ] — left

Combining formats

DateTime dt = DateTime.Now;
Console.WriteLine($"Today {dt:dddd, dd MMMM yyyy}, time {dt:HH:mm}");

Interpolation with different data types

bool ok = true;
Console.WriteLine($"Operation {(ok ? "successful" : "error")}");

Multiline strings with interpolation

Recently, raw string literals and multiline interpolated strings showed up too:

string user = "Timur";
int score = 100;

Console.WriteLine($"""
    Congrats, {user}!
    Your score: {score}
    """);

Nested interpolation and calculations

You can call methods, format their result, and insert into the string:

double[] temps = { 23.4, 25.1, 21.9 };
Console.WriteLine($"Average temperature: {temps.Average():F1}°C");

Example with a table (alignment + format)

Formatting and alignment in a table using interpolation

double[] prices = { 123.4, 8.9, 5643.0 };
for (int i = 0; i < prices.Length; i++)
    Console.WriteLine($"Product {i + 1}: {prices[i],10:F2} euro");

Result:

Product 1:    123.40 euro
Product 2:      8.90 euro
Product 3:   5643.00 euro

4. Escaping and Interpolation Together

You can use escape characters and interpolation at the same time:

string user = "Masha";
Console.WriteLine($"Hi, \"{user}\"!\nNice to meet you.");

Output:

Hi, "Masha"!
Nice to meet you.

If you combine this with verbatim strings, just put $ first, then @ (though you can swap them — doesn't matter):

string path = "C:\\Temp";
Console.WriteLine($@"File found at: ""{path}""");
2
Task
C# SELF, level 9, lesson 2
Locked
Data table with alignment and formatting.
Data table with alignment and formatting.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION