String
interpolationThis C# feature inserts values into a string
with simple syntax. It is similar to string.Format
, but variables may be accessed directly.
String
interpolation can use array accesses, expressions and method calls as insertion values. Its performance is similar to string.Format
calls.
Here is a simple example of the string
interpolation syntax. We precede the interpolation literal with a "$" sign.
string
literal at the "{dogs}" position.using static System.Console; class Program { static void Main() { int cats = 100; int dogs = 2; // Create a string with string interpolation syntax. string animals = $"cats = {cats} and dogs = {dogs}"; // Call Console.WriteLine. WriteLine(animals); } }cats = 100 and dogs = 2
Here we access an element from an array in a string
interpolation. We use the "$" sign and place the array access within the curly brackets.
string
. We can use "result" like any other string
.using System; class Program { static void Main() { int[] values = { 10, 20, 30 }; // Test string interpolation with array values. string result = $"The second value is {values[1]}"; Console.WriteLine(result); } }The second value is 20
We can insert an expression in a string
interpolation. Here we insert the id variable multiplied by 10. The result of the expression is inserted as an int
.
using System; class Program { static void Main() { int id = 100; // We can use an expression with a string interpolation. string result = $"The multiplied ID is {id * 10}"; Console.WriteLine(result); } }The multiplied ID is 1000
A method can be called with a string
interpolation. Here we call the Paws()
method with an argument of 5. String
interpolations support any C# expressions that return values.
using System; class Program { static int Paws(int cats) { // Four paws per cat. return cats * 4; } static void Main() { // A string interpolation can call a method. string result = $"The paw count is {Paws(5)}"; Console.WriteLine(result); } }The paw count is 20
In string
interpolation we must be careful of the way use we brace characters. The string
interpolation parser treats these specially, so we must escape them.
class Program { static void Main() { // We cannot use some characters in the same way. string result = $"Size is }"; } }Program.cs(6,35,6,36): error CS8086: A '}' character must be escaped (by doubling) in an interpolated string.
Here we print the close-bracket (brace) character directly by doubling it. Please notice only one char
is printed when we specify 2 in the interpolated string
.
string
interpolation syntax, but it is needed to have special delimiter characters.class Program { static void Main() { // Double the char. string result = $"My favorite char is }}."; System.Console.WriteLine(result); } }My favorite char is }.
We have to have an open and close delimiter to compile a string
interpolation. For completeness, here is the error when we do not close an interpolated expression.
class Program { static void Main() { string result = $"Hello, {"; } }error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. error CS1010: Newline in constant error CS1002: ; expected
Does string
interpolation provide good performance? Here I tested string
interpolation with two local variables. I use int.Parse
to avoid any possible compiler optimizations.
string
interpolation with two variable accesses. Its value is tested for correctness.string
concat expression. The plus signs are compiled to a string.Concat
method call.string.Format
. We use substitution markers to insert the values of cats and dogs.String.Concat
was fastest. String
interpolation (version 1) and string.Format
were about the same speed.using System; using System.Diagnostics; const int _max = 1000000; int cats = int.Parse("10"); int dogs = int.Parse("2"); // Version 1: use string interpolation. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { string result = $"{cats} cats and {dogs} dogs"; if (result[0] != '1') { return; } } s1.Stop(); // Version 2: use string concat. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { string result = cats + " cats and " + dogs + " dogs"; if (result[0] != '1') { return; } } s2.Stop(); // Version 3: use string format method. var s3 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { string result = string.Format("{0} cats and {1} dogs", cats, dogs); if (result[0] != '1') { return; } } s3.Stop(); Console.WriteLine(s1.Elapsed.TotalMilliseconds); Console.WriteLine(s2.Elapsed.TotalMilliseconds); Console.WriteLine(s3.Elapsed.TotalMilliseconds); 66.8248 ms, String interpolation 38.0441 ms, Concat (+) 143.8717 ms, String Format
In these examples, we used string
interpolation syntax. Any value-returning C# expression can be inserted into a string
. Performance is similar to the Format method.