String Interpolation In C#

Introduction

C# string interpolation is a method of concatenating, formatting, and manipulating 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. 

{<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, the author, is a part of the string interpolation. 

string author = "Mahesh Chand";  
string hello = $"Hello {author} !";  
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. 

// Simple String Interpolation  
string author = "Mahesh Chand";  
string book = "Programming C#";  
int year = 2018;  
decimal price = 45.95m;  
string hello = $"{author} is an author of {book} . \n" +  
$"The book price is ${price} and was published in year {year}. ";  
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. 

// Use spacing - add 20 chars  
Console.WriteLine($"{author}{book, 20}");

Listing 3.

The following code example in Listing 4 uses an expression in a string interpolation operation. 

// Use an expression  
Console.WriteLine($"Book {book} price is {(price < 50 ? "50" : "45")} .");

Listing 4.

Learn more about string concatenation here: 6 Effective Ways to Concatenate Strings in C#.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.