String interpolation is a very useful and expressive feature of C# that simplifies the creation of dynamic character strings. Instead of using methods like String.Format or concatenating parts using the + operator, interpolation allows you to insert expressions directly into a string in a clear and readable way.
What is String Interpolation?
String interpolation in C# is a feature that allows you to embed expressions within string literals. This is done by prefixing the string with the $ character and including expressions inside curly braces {}. The compiler replaces the expressions with their results, generating the final string.
Example:
int age = 25;
string message = $"I am {age} years old.";
When you add the $ symbol before the quotation marks, the compiler understands that the content inside the {} braces should be treated as C# code. In the example above, the age variable is embedded in the string, resulting in the output “I am 25 years old.” This approach makes the code more readable and concise.
Comparing String Interpolation with String.Format
Before string interpolation was introduced in C#, one of the most common ways to construct dynamic character strings was through the String.Format method. Although both techniques serve the same purpose, string interpolation offers some advantages that make it a more modern and convenient choice.
The main difference between string interpolation and String.Format is the clarity of the syntax. With String.Format, you use numeric placeholders inside the string and pass the corresponding values as arguments:
Example:
int age = 25;
string name = "John";
string message = String.Format("My name is {0} and I am {1} years old.", name, age);
In this example, the String.Format method creates the string “My name is John and I am 25 years old.” The {0} placeholder is replaced by the value of the name variable, and the {1} placeholder is replaced by the value of the age variable. The values are inserted in the respective positions indicated by the numbers inside the braces.
Although String.Format is an effective solution for creating dynamic strings, it requires the developer to maintain the correct correspondence between the placeholder indices and the provided arguments, which can be error-prone, especially in complex strings. Additionally, the use of numeric indices can make the code less readable compared to more modern alternatives like string interpolation.
Specifying Formats Within the String
One of the advantages of string interpolation is the ability to specify the output format of expressions. This is especially useful for formatting numbers and dates. You can specify a format string inside the braces after the expression by using the colon : followed by the desired format:
Example:
double value = 5934.86;
string message = $"The formatted value is {value:C}.";
In the example above, the C format is used to format the number as currency. The result of this string would be something like “The formatted value is $5,934.86.” Other format examples include:
N: number with thousand separators.F: fixed-point number with decimal places.P: percentage.
For dates, you can use predefined formats or create custom formats.
Example:
DateTime currentDate = DateTime.Now;
string message = $"Current date: {currentDate:dd/MM/yyyy}";
In the example above, the format dd/MM/yyyy is used to display the date in day/month/year format.
Using the Ternary Conditional Operator ?:
The ternary conditional operator ?: is a concise way to express a condition and can be used within a string interpolation. It evaluates a boolean expression and returns one of two values depending on the result. When inserted into a string, the entire ternary expression should be enclosed in parentheses, as follows:
Example:
bool passed = true;
string message = $"You have {(passed ? "passed" : "failed")}!";
In this example, the ternary operator checks the value of the passed variable, and if it’s true, it inserts “passed” into the string; otherwise, it inserts “failed”. Since the variable passed is true, the result will be “You have passed!”
Conclusion
String interpolation in C# represents an evolution over the String.Format method, offering a more intuitive, flexible, and readable syntax. While String.Format is still useful in some cases, string interpolation stands out as the preferred choice for building dynamic strings in modern C#, especially in situations that require clean and expressive code.