C# String Interpolation


The general definition of interpolation can be either (1) the insertion of something of a different nature into something else or (2) a remark interjected in a conversation. The word has a similar meaning in C# strings.

String Interpolation

An interpolated string is a string literal that might contain interpolated expressions. The $ special character identifies a string literal as an interpolated string. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

To identify a string literal as an interpolated string, prepend it with the $ symbol. You cannot have any white space between the $ and the that starts a string literal. Doing so causes a compile-time error.

String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature. There is an example at the Microsoft site that show string interpolation and composite formatting. A slightly modified version is listed below.

string name = "Website Reader";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);

// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Website Reader! Today is Wednesday, it's 19:40 now.

We can do some string formatting here. We can use ToUpper() and any other available methods such as ToLower(), Substring(), Trim(), TrimStart(), TrimEnd() and Replace(), among others.

Console.WriteLine($"Hello, {name.ToUpper()}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// and some other examples:
// {name.ToUpper().Substring(0,3)}
// {name.Substring(0,7).ToUpper()}
// {date.DayOfWeek}     // will return Monday or Tuesday... 
// {date.Hour}
// Console.WriteLine($"Today: {date.ToLongDateString()}");
// Console.WriteLine($"Today: {date.ToShortDateString()}");
// Console.WriteLine($"{name.Replace("e","q")}"); // Wqbsitq Rqadqr

Composite Formatting

The general definition of composite as an adjective is: made up of various parts or elements.

The Microsoft web page says: “The .NET composite formatting feature takes a list of objects and a composite format string as input. A composite format string consists of fixed text intermixed with indexed placeholders, called format items, that correspond to the objects in the list. The formatting operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.” At that page they have a code fragment as an example, shown below.

string name = "Fred";
String.Format("Name = {0}, hours = {1:hh}", name, DateTime.Now);

Each format item takes the following form and consists of the following components shown below. The matching braces (“{” and “}”) are required.

{ index[,alignment][:formatString]}

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so o

string primes;
primes = String.Format("Some prime numbers: {0}, {1}, {2}, {3}",2, 3, 5, 7 );
Console.WriteLine(primes);
// The example displays the following output:
//      Some prime numbers: 2, 3, 5, 7
//
//
string multiple = String.Format("0x{0:X} {0:E} {0:N}", Int64.MaxValue);
Console.WriteLine(multiple);
// The example displays the following output:
//      0x7FFFFFFFFFFFFFFF 9.223372E+018 9,223,372,036,854,775,807.00

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string such as : “0x{0:X} {0:E} {0:N}” as shown in the above code listing.

Here is another example. Both types of formatting produce equivalent results. Console.WriteLine exposes the same functionality as String.Format. The only difference between the two methods is that String.Format returns its result as a string, while Console.WriteLine writes the result to the output stream associated with the Console object.

string FormatString1 = String.Format("{0:dddd MMMM}", DateTime.Now);
string FormatString2 = DateTime.Now.ToString("dddd MMMM");

Below is another example.

string myName = "Fred";
Console.WriteLine(String.Format("Name = {0}, hours = {1:hh}, minutes = {1:mm}",
      myName, DateTime.Now));
// Depending on the current time, the example displays output like the following:
//    Name = Fred, hours = 11, minutes = 30