C# – Use string interpolation instead of string.Format

Using string.Format() is error prone and can lead to runtime exceptions. Using string interpolation prevents these problems (and it’s more readable).

This article shows the two common mistakes you can make when using string.Format(), resulting in runtime exceptions, and shows how you can use string interpolation to prevent these problems.

1 – FormatException: Format string contains invalid placeholder

The following format string has four placeholders, but only three values getting passed in.

string.Format("Name={0} City={1} Conference={2} Division={3}", nflTeam.Name, nflTeam.City, nflTeam.Conference);
Code language: C# (cs)

This results in the following FormatException when you run the code:

System.FormatException: ‘Index (zero based) must be greater than or equal to zero and less than the size of the argument list.’

It should be noted that the compiler does show the following warning for this:

IDE0043 Format string contains invalid placeholder

Most coders ignore warnings though, so it’s unlikely that you would actually notice this problem. Side note: This is where it makes sense to treat warnings as errors, so they must be dealt with.

2 – FormatException: Input string was not in the correct format

The following format string is malformed – instead of {3} it has 3}.

string.Format("Name={0} City={1} Conference={2} Division=3}", nflTeam.Name, nflTeam.City, nflTeam.Conference);
Code language: C# (cs)

When you run this code, you get the following FormatException:

FormatException: ‘Input string was not in a correct format.’

The compiler doesn’t detect this problem and doesn’t show any warnings or errors.

Solution – Use string interpolation instead of string.Format()

Using string.Format() is risky, because it’s so easy to make mistakes and not find out there’s a problem until you have a runtime exception.

The simplest solution is to use string interpolation instead of string.Format(). This prevents these mistakes, and therefore prevents runtime exceptions.

Here’s how you use string interpolation:

 var tmp = $"Name={nflTeam.Name} City={nflTeam.City} Conference={nflTeam.Conference} Division={nflTeam.Divison}";
Code language: C# (cs)

Not only does this prevent runtime exceptions, but I find it to be much more readable than using string.Format().