String Interpolation Definition
String interpolation in C# is a feature that enables you to write more readable code to create formatted strings.
String Interpolation Usage
Instead of using positional parameters in String.Format:
string name = "David Byer";
int age = 23;
string text = String.Format("{0} is {1} years old.", name, age); // David Byer is 23 years old.
With string interpolation, we can write more readable and convenient code by using the special character $
like this:
string name = "David Byer";
int age = 23;
// prefacing the string with $
string text = $"{name} is {age} years old.";
// David Byer is 23 years old.
Advanced Usage
By using string interpolation, we can include more than just simple variables in our result string. We can also include :
Arithmetic expressions
1- Addition
string result = $"SUM of 5 and 6 is : {5 + 6}"; // SUM of 5 and 6 is : 11
2- Multiplication
string result = $"Multiplication of 3 and 4 is : {3 * 4}"; // Multiplication of 3 and 4 is : 12
And other arithmetic expressions: ( -, /, ... ).
Methods
1- C# Methods
Including the method Math.Max which returns the larger of two numbers passed as arguments of the method.
string result = $"The maximum number between 1 and 55 is : { Math.Max(1, 55) }"; // The maximum number between 1 and 55 is : 55
2- Custom Methods
The following method returns the category of a person depending on its age passed as an argument of the method.
public string PersonCategory(int age) {
if (age < 15)
return "Children";
else if (age >= 15 && age < 25)
return "Youth";
else if (age >= 25 && age < 65)
return "Adults";
else
return "Seniors";
}
Including the PersonCategory
method in a result string :
string result = $"This person belongs to the category of : {PersonCategory(27)}"; // This person belongs to the category of : Adults
Note
String interpolation is available in C# 6 or later.