Home
Map
String Interpolation ExamplesUse string interpolation with arrays, ints, expressions and method calls.
C#
This page was last reviewed on Jan 3, 2024.
String interpolation. This C# feature inserts values into a string with simple syntax. It is similar to string.Format, but variables may be accessed directly.
Other features. String interpolation can use array accesses, expressions and method calls as insertion values. Its performance is similar to string.Format calls.
string.Format
Initial example. Here is a simple example of the string interpolation syntax. We precede the interpolation literal with a "$" sign.
Info Cats is an integer local variable. It equals 100 (there are lots of cats). It is inserted into the "{cats}" part of the literal.
And Dogs equals 2. It is inserted into the interpolated 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
Array elements. 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.
Result The second array element is inserted into the resulting 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
Expressions. 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
Method calls. 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
Character error. 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.
Character error, fix. 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.
Note This is a downside to 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 }.
Error, close delimiter. 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.
Tip Make sure to correctly close all the interpolated expressions if you wish to compile your program.
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
Benchmark. 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.
int.Parse
Version 1 This loop tests a string interpolation with two variable accesses. Its value is tested for correctness.
Version 2 This version uses a string concat expression. The plus signs are compiled to a string.Concat method call.
string.Concat
Version 3 Here we use string.Format. We use substitution markers to insert the values of cats and dogs.
Result 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
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 3, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.