# String Interpolation
You are familiar with this code.
using System;
class MainClass
{
public static void Main ()
{
int age = 64;
string name = "John";
Console.WriteLine("{0} is {1} years old", name, age);
}
}
2
3
4
5
6
7
8
9
10
11
Replace line 9 with this code
Console.WriteLine($"{name} is {age} years old");
Run it in your IDE. Did it work?
What is the difference between the two code?
# Explanation
The word interpolation means inserting something into something else. In Urdu it means شامل کرنا.
When a $
is placed before a string literal, it becomes an interpolated string.
In this string $"{name} is {age} years old"
, you can see name
and age
are inserted inside a string.
In simple terms, with interpolation, you can simply refer to the variables by their names.
# Expression Interpolation
Besides variables, you can also use expressions.
using System;
class MainClass
{
public static void Main ()
{
string name = "John";
int age = 40;
int yearOfBirth = 1980;
Console.WriteLine($"{name} is {age} years old");
Console.Write($"In the year 2001, {name} was {2001 - yearOfBirth} years old");
}
}
2
3
4
5
6
7
8
9
10
11
12
13
Did you notice the {2001 - yearOfBirth}
? Compiler will perform the calculation and insert the result into the string.
# Assign interpolated string to a variable
In the above examples, we have passed interpolated string to the Console.Write
and Console.WriteLine
methods.
You can assign interpolated string to a variable.
string result = $"In the year 2001, {name} was {2001 - yearOfBirth} years old";
← Exercise 6 Example 1 →