JetBrains Rider 2019.2 Help

Code Inspection: Possibly unintended string interpolation

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(), etc. — 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 simply 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: 20 August 2019

See Also