Understanding String Interpolation In C#

Understanding String Interpolation In C#
 
String Interpolation C# 
 
The string interpolation feature allows an easier way to format and manipulate strings. This feature was introduced in C# 6.
 
Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.
 
Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax. 
  1. {<interpolatedExpression>[,<alignment>][:<formatString>]}  
Where: 
  • interpolatedExpression - 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 result of the interpolated expression. 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 following code example in Listing 1 concatenates a string where an object, author as a part of the string interpolation. 
  1. string author = "Mahesh Chand";  
  2. string hello = $"Hello {author} !";  
  3. Console.WriteLine(hello);  
Listing 1.
 
The output of Listing 1 looks like Figure 1.
 
String Interpolation 
 
Figure 1.
 
The following code example in Listing 2 creates a string by concatenating values of four different types of variables. 
  1. // Simple String Interpolation  
  2. string author = "Mahesh Chand";  
  3. string book = "Programming C#";  
  4. int year = 2018;  
  5. decimal price = 45.95m;  
  6. string hello = $"{author} is an author of {book} . \n" +  
  7. $"The book price is ${price} and was published in year {year}. ";  
  8. Console.WriteLine(hello);  
Listing 2.
 
The output of Listing 2 looks like Figure 2.
 
 
 
Figure 2.
 
The following code example in Listing 3 creates a string with spacing and adds 20 characters after the first object. 
  1. // Use spacing - add 20 chars  
  2. Console.WriteLine($"{author}{book, 20}");  zListing 3.
The following code example in Listing 4 uses an expression in a string interpolation operation. 
  1. // Use an expression  
  2. Console.WriteLine($"Book {book} price is {(price < 50 ? "50" : "45")} .");  
Listing 4.