How to Use string interpolation instead of string.Format in C#
By Tan Lee Published on Mar 04, 2025 138
This article illustrates two common mistakes that occur when using string.Format()
, causing runtime exceptions, and demonstrates how to avoid them using string interpolation.
FormatException: Format string contains invalid placeholder
In the following example, the format string expects four placeholders, but only three arguments are provided:
string message = string.Format("Employee: {0}, Age: {1}, Department: {2}, ID: {3}", employee.Name, employee.Age, employee.Department);
This results in a FormatException
at runtime:
System.FormatException: 'Index (zero based) must be greater than or equal to zero and less than the size of the argument list.'
The compiler does provide a warning (IDE0043: Format string contains invalid placeholder
), but many developers overlook warnings, making this an easy mistake to miss.
FormatException: Input string was not in the correct format
A simple syntax error, such as a misplaced closing brace, can break the string.Format()
method:
string message = string.Format("Employee: {0}, Age: {1}, Department: 2}", employee.Name, employee.Age);
Running this code results in:
System.FormatException: 'Input string was not in a correct format.'
Unlike the first mistake, the compiler does not detect this issue, making it even more dangerous.
Solution - Use string interpolation instead of string.Format()
String interpolation eliminates these risks by embedding variables directly within the string:
string message = $"Employee: {employee.Name}, Age: {employee.Age}, Department: {employee.Department}, ID: {employee.ID}";
This approach prevents formatting errors while improving readability. The compiler ensures that all variables exist and are correctly referenced, reducing the likelihood of runtime exceptions.
Avoid string.Format()
whenever possible in favor of string interpolation. It makes code easier to read, prevents common mistakes, and eliminates unnecessary runtime exceptions.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization