String Format Problems

ID

csharp.string_format_problems

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

CSharp

Tags

format, reliability

Description

Reports string.Format (or String.Format) calls whose composite format literal does not line up with the number of supplied arguments: either there are too few arguments (a FormatException at run time) or there are unused trailing arguments (a likely copy-paste mistake).

Rationale

string.Format("{0} {1}", x) throws at run time, but the bug is silent until the call is executed. string.Format("{0}", x, y) does not throw, but y is dead — the formatted output never references it, which usually means the developer intended a second placeholder and forgot to add it.

var s1 = string.Format("{0} {1}", first);              // FLAW — 2 placeholders, 1 arg
var s2 = string.Format("{0}", first, second);          // FLAW — 1 placeholder, 2 args
var s3 = string.Format("no placeholder", first);       // FLAW — extra arg ignored
var s4 = string.Format("{0} {0}", first);              // OK — single arg reused
var s5 = string.Format("{0} {1}", first, second);      // OK — counts match

Remediation

Adjust either the literal or the argument list so the highest placeholder index plus one equals the number of arguments after the format string. For dynamic shapes, switch to string interpolation ($"{first} {second}") which is checked at compile time.