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:
-
String.Format
-
StringBuilder.AppendFormat
-
Console.Write
-
Console.WriteLine
-
TextWriter.Write
-
TextWriter.WriteLine
-
Debug.WriteLine(String, Object[])
-
Trace.TraceError(String, Object[])
-
Trace.TraceInformation(String, Object[])
-
Trace.TraceWarning(String, Object[])
-
TraceSource.TraceInformation(String, Object[])
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:
- the format string is not a
const
.
var pattern = "{0} {1} {2}";
var res = string.Format(pattern, 1, 2); // Compliant, non-constant string are not recognized
- the argument is not an inline creation array.
var array = new int[] {};
var res = string.Format("{0} {1}", array); // Compliant the rule does not check the size of the array