Why is this an issue?

Composite format strings in C# are evaluated at runtime, which means they are not verified by the compiler. Introducing an ill-formed format item, or indexing mismatch can lead to unexpected behaviors or runtime errors. The purpose of this rule is to perform static validation on composite format strings used in various string formatting functions to ensure their correct usage. This rule validates the proper behavior of composite formats when invoking the following methods:

Noncompliant code example

s = string.Format("[0}", arg0); // Noncompliant: square bracket '[' instead of curly bracket '{'
s = string.Format("{{0}", arg0); // Noncompliant: double starting curly brackets '{{'
s = string.Format("{0}}", arg0); // Noncompliant: double ending curly brackets '}}'
s = string.Format("{-1}", arg0); // Noncompliant: invalid index for the format item, must be >= 0
s = string.Format("{0} {1}", arg0); // Noncompliant: two format items in the string but only one argument provided

Compliant solution

s = string.Format("{0}", 42); // Compliant
s = string.Format("{0,10}", 42); // Compliant
s = string.Format("{0,-10}", 42); // Compliant
s = string.Format("{0:0000}", 42); // Compliant
s = string.Format("{2}-{0}-{1}", 1, 2, 3); // Compliant
s = string.Format("no format"); // Compliant

Exceptions

The rule does not perform any checks on the format specifier, if present (defined after the :). Moreover, no issues are raised in the following cases:

Resources

Documentation