Description

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 statically validates the good behavior of composite formats when calling the methods of 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[]) and TraceSource.TraceInformation(String, Object[]).

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";

Exceptions

  • No issue is raised if the format string is not a const.

var pattern = "{0} {1} {2}";
var res = string.Format(pattern, 1, 2); // Compliant, not const string are not recognized
  • No issue is raised if the argument is not an inline creation array.

var array = new int[] {};
var res = string.Format("{0} {1}", array); // Compliant we don't know the size of the array
  • This rule doesn’t check whether the format specifier (defined after the :) is actually valid.


Implementation Specification

(visible only on this page)

Message

XXXX


(visible only on this page)

is duplicated by: S3941

on 10 Dec 2015, 09:07:59 Tamas Vajk wrote:

\[~ann.campbell.2] Removed the performance label, as the performance impact is insignificant.

on 10 Dec 2015, 14:44:05 Ann Campbell wrote:

I’ve updated SQALE characteristic to match [~tamas.vajk]