String interpolation is used to concatenate, format, and manipulate strings in C#. It provides more readable and convenient syntax to create formatted strings than a native string composite format feature.
Interpolated string structure:
String interpolation syntax starts with a ‘$
’ symbol and you can't leave any white space between $
and the ", also expressions will be defined within a bracket {}
as shown below,
{<interpolationExpression>[,<alignment>][:<formatString>]}
Elements in square brackets are optional,
Element | Description |
---|---|
interpolationExpression |
The expression that produces a result to be formatted. |
alignment |
The constant expression whose value defines the minimum number of characters in the string representation of the expression result. If positive, the string representation is right-aligned; if negative, it's left-aligned. |
formatString |
A format string that is supported by the type of the expression result. |
The code snippet concatenates the name and website variables with a string using string interpolation.
string name = "Sabari";
string website = "Techiclues.com";
// Composite formatting
Console.WriteLine("Welcome {0}!, {1} is a developer community website.", name, website);
// String interpolation
Console.WriteLine($"Welcome {name}!, {website} is a developer community website.");
Output:
Welcome Sabari!, Techiclues.com is a developer community website.
Welcome Sabari!, Techiclues.com is a developer community website.
The below code snippet concatenates the car, model, and price variables with a string using string interpolation.
string car = "Audi A1";
string model = "Sportback";
string price = "45,000";
Console.WriteLine($"Prices for an {car} {model} start around ${price}");
Output:
Prices for an Audi A1 Sportback start around $45,000
The following example constructs a string with spacing and appends 10 characters after the first string.
string car = "Audi A1";
string model = "Sportback";
// {car, 10} - adds 10 characters space from the first object.
Console.WriteLine($"{car}{model,15} is a good premium car");
Output:
Audi A1 Sportback is a good premium car
String interpolation and expression is used in the below code example,
string name = "John";
int age = 25;
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
Output:
John is 25 years old.
Comments (0)