Sabari M Sabari M
Updated date Oct 22, 2020
String Interpolation In C#

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!!!

ABOUT THE AUTHOR

Sabari M
Sabari M
Software Professional, India

IT professional with 14+ years of experience in Microsoft Technologies with a strong base in Microsoft .NET (C#.Net, ASP.Net MVC, ASP.NET WEB API, Webservices,...Read More

https://www.techieclues.com/profile/alagu-mano-sabari-m

Comments (0)

There are no comments. Be the first to comment!!!
×