C#
Summary - String basics
Combine interpolation, concatenation and Format to write a business card.
Summary - String basics
In this group you learned to create strings, use interpolation, concatenation, String.Format and verbatim strings. Now you will combine them to produce a business card text.
Across two exercises you will first write the name and age with interpolation, then a multi-line contact block with a verbatim string. Each tool fits its own spot best.
Exercise Business card line with interpolation
Declare name and age with the given values. Use interpolation to build info as "Alex - 28 years old" and print it with Console.WriteLine.
Show example solution
Declare name and age, then assign $"{name} - {age} years old" to info and print it.
Example solution:
using System;
class Program
{
static void Main()
{
string name = "Alex";
int age = 28;
string info = $"{name} - {age} years old";
Console.WriteLine(info);
}
}
Exercise Contact block with verbatim
Declare a contact variable as a verbatim string. Its content should be exactly three lines: Contact:, email: alex@example.com, phone: 555-1234. You must use the @ prefix; line breaks in your code stay as actual lines. Then print it with Console.WriteLine.
Show example solution
Write three lines with real line breaks inside a verbatim string.
Example solution:
using System;
class Program
{
static void Main()
{
string contact = @"Contact:
email: alex@example.com
phone: 555-1234";
Console.WriteLine(contact);
}
}
The string tools side by side
You now know four tools: + for concatenation, $"..." for interpolation, String.Format for placeholders and @"..." for verbatim. Which one to pick depends on the situation.
For short, two-piece joins + is enough; with many variables interpolation reads better; String.Format suits custom placeholder order; verbatim is cleanest for multi-line or backslash-heavy text.
Test yourself
-
What is the output of "Price: " + 25 + " USD"?
Console.WriteLine("Price: " + 25 + " USD");
- Price: 25
- Price: 25 USD
- Price: 25 USD25
- 25 USD
Show answer
Price: 25 USD — Correct. + concatenates; the number is converted to text automatically.
-
Complete the interpolation expression
string name = "Alex";
int age = 28;
string info = $"{name}, ____ years old.";
Show answer
string name = "Alex";
int age = 28;
string info = $"{name}, {age} years old.";
Next lesson: The if statement