String Interpolation is one of the C# 6 feature, the $
special character identifies a string literal as an interpolated string.
We normally use String.Format method to construct strings, this method is useful but its usage is a bit difficult, you have to mention the number placeholder in the format string which should be lineup with separate specified arguments.
String.Format Usage:
string.Format("I have {0} cars, {1} motorbike and {2} bicycle.", 2, 3, 1);
// Output
// I have 2 cars, 3 motorbike and 1 bicycle.
Using string interpolation, we can easily construct, format the string easily and quickly. Syntax of string interpolation should start with a ‘$’ symbol and expressions should be defined within a bracket {}.
string firstName = "John";
string lastName = "Mathews";
string strMessage = $"Hi {firstName} {lastName}, Welcome!!!";
Console.WriteLine(strMessage);
// Output
// Hi John Mathews, Welcome!!!
The below example shows how to creates a string by concatenating the values of multiple types of variables.
string firstName = "John";
string lastName = "Mathews";
int years = 35;
string strMessage = $"{firstName} {lastName} is {years} years old.";
Console.WriteLine(strMessage);
// Output
// John Mathews is 35 years old.
The below example explains how to create a string with 15 spacing before the text (i.e, years)
string firstName = "John";
string lastName = "Mathews";
int years = 35;
string strMessage = $"{firstName} {lastName} {years, 15}";
Console.WriteLine(strMessage);
// Output
// John Mathews 35
Expression:
The below example uses an expression in a string interpolation operation and the conditional expression should be parenthesized.
string firstName = "John";
string lastName = "Mathews";
int age = 35; // 35 or 1
string strMessage = $"{firstName} {lastName} is {age} year{(age == 1 ? "" : "s")} old!!!";
Console.WriteLine(strMessage);
// Input 1 : age = 35
// Output - 1
// John Mathews is 35 years old!!!
// Input 2 : age = 1
// Output - 2
// John Mathews is 1 year old!!!
Comments (0)