Why is this an issue?

A composite format string is a string that contains placeholders, represented by indices inside curly braces "{0}", "{1}", etc. These placeholders are replaced by values when the string is printed or logged.

Because composite format strings are interpreted at runtime, rather than validated by the compiler, they can contain errors that lead to unexpected behaviors or runtime errors.

This rule validates the correspondence between arguments and composite formats when calling the following methods:

Exceptions

var pattern = "{0} {1} {2}";
var res = string.Format(pattern, 1, 2); // Incorrect, but the analyzer doesn't raise any warnings here
var array = new int[] {};
var res = string.Format("{0} {1}", array); // Compliant; we don't know the size of the array

How to fix it

A composite format string contains placeholders, replaced by values when the string is printed or logged. Mismatch in the format specifiers and the arguments provided can lead to incorrect strings being created.

To avoid issues, a developer should ensure that the provided arguments match format specifiers.

Moreover, use string interpolation when possible.

Instead of

string str = string.Format("Hello {0} {1}!", firstName, lastName);

use

string str = $"Hello {firstName} {lastName}!";

With string interpolation:

Code examples

Noncompliant code example

s = string.Format("{0}", arg0, arg1); // Noncompliant, arg1 is declared but not used.
s = string.Format("{0} {2}", arg0, arg1, arg2); // Noncompliant, the format item with index 1 is missing, so arg1 will not be used.
s = string.Format("foo"); // Noncompliant; there is no need to use "string.Format" here.

Compliant solution

s = string.Format("{0}", arg0);
s = string.Format("{0} {1}", arg0, arg2);
s = "foo";