Learn C# · lesson 5 of 61 · about 7 minutes
String Interpolation and Comments
Build a status line with $"...{x}...", format numbers, and explain your code with comments.
What you'll learn
- Use interpolated strings
- Format with :F2, :D2 and alignment
- Write // and /* */ comments
Interpolation
Joining with + gets messy fast. Put $ before a string and anything in { } is worked out and dropped into the text: $"{hero} has {hp} HP".
You can format inside the braces:
| Format | Meaning | Example |
|---|---|---|
| {x:F2} | 2 decimal places | 1.50 |
| {x:D2} | at least 2 digits | 07 |
| {x,5} | right-align in 5 | " 30" |
A status line
string hero = "Ada";
int hp = 30;
double speed = 1.5;
Console.WriteLine($"{hero} has {hp} HP");
Console.WriteLine($"Speed: {speed:F2}");
Console.WriteLine($"[{hp,5}] [{7:D3}] {hp * 2}");Output
Ada has 30 HP
Speed: 1.50
[ 30] [007] 60Comments
Comments are notes for humans: // turns the rest of a line into a comment, and /* ... */ can cover several lines. The compiler ignores both. Use them to say *why* the code does something.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.