JetBrains Rider 2024.3 Help

Code inspection: Possibly unintended string interpolation instead of format string template

The following code looks fine at first glance, but it will return Hello 0! instead of Hello world!, as might be expected.

Console.WriteLine($"Hello {0}!", "world");

For years, string formatting methods — String.Format(), Console.WriteLine(), and so on — were our favorite ways to combine hard-coded string literals with variable values. That's why a number in braces {} looks very natural inside the first argument. But the string interpolation notation, which gradually replaces string formatting methods, also uses braces for inserting expressions into the target string. So in the above example, the first argument prefixed with the $ will be processed as an interpolated string, and only after that will it be passed to the formatting method. At this point, the {0} placeholder will be already replaced with its calculated value, that is 0, and the formatting method will ignore the second argument.

JetBrains Rider suggests removing the $ prefix from the first argument so that the string formatting method could work as expected:

Console.WriteLine("Hello {0}!", "world");
Last modified: 11 February 2024