String Interpolation Header Image

Interpolation: The Best Way to Add Variables to Strings

There are multiple different ways to insert a variable into a string but the best way is through string interpolation. The most important thing to me about working code is its readability. This is why I believe every .Net developer should make the switch, from methods such as “string.Format()”, to string interpolation.

String Interpolation Syntax

String interpolation has very simple syntax – which is why I like it so much. You just add the character $ before your string literal to indicate that the string will be interpolated. Your variable can then be added to the string by enclosing it in {}. The syntax allows the variable to be added inline which makes the code more understandable.

public class Program
{
  static void Main(string[] args)
  {
    //Example of string interpolation.
    var dateNow = DateTime.Now;
    Console.WriteLine(
      $"{dateNow} was when I found the best syntax for adding variables to a string!"
    );

    //Returns 19/02/2021 09:00:00 was when I found the best syntax for adding variables to a string!
  }
}

The main alternatives to string interpolation are the string format method, string concatenation, and using a string builder. If you compare the syntax for the other approaches – it is clear how much more readable string interpolation is.

public class Program
{
  static void Main(string[] args)
  {
    //Using String.Format()
    var dateNow = DateTime.Now;
    Console.WriteLine(
      String.Format("{0} was when I stopped using this syntax for adding variables to a string!", dateNow)
    ); 

    //Using string concatenation 
    Console.Writeline(dateNow + "was when I stopped using this syntax for adding variables to a string!")

    //Using StringBuilder
    StringBuilder message = new StringBuilder();
    message.Append(dateNow);
    message.Append(" was when I stopped using this syntax for adding variables to a string!");
    Console.WriteLine(message); ;
  }
}

As well as adding variables in line you can directly include more complex code. In the above example, I could have directly called the DateTime function in the interpolated string instead of first assigning it to a variable. You can also include conditional operators but to do so you must remember to wrap the expression in parenthesis. This is because there is optional syntax in string interpolation that reserves the special character “:”. The parenthesis breaks out this character. For more information on the optional syntax, I recommend taking a look at the Microsoft documentation.

public class Program
{
  static void Main(string[] args)
  {
    //Example of an interpolated string using a ternary operator.
     var testNumber = 6;
     Console.WriteLine(
      $"The test number is {(testNumber > 5 ? "greater than 5" : "less than or equal to 5")}"
    );
    //Returns "The test number is greater than 5"
  }
}

Performance

String interpolation is not the most performant way to add variables to a string. This is not going to be an issue most of the time but it is something to be aware of if you are optimizing your solution to be as fast as possible. The following article outlines an example of a string interpolation speed test. The performance of interpolation is very similar to the string format. String interpolation syntax is turned into the string format function at compile-time, causing similar performance times. Generally, you will not notice the slower performance but if you are seeing performance issues then string builder is probably the way to go.

Summary

I hope this short post on string interpolation has convinced you to start using it if you aren’t already. I believe it is the best way to add a variable to a string and makes it much easier to understand what is going on. It is a very simple way to improve the clarity of your code with only a minor performance hit when compared to using a string builder.

If you enjoyed this article, make sure to check out more of my .Net content!

Leave a Reply