String Concat In Loop

ID

csharp.string_concat_in_loop

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Efficiency

Language

CSharp

Tags

code-style

Description

Reports string concatenation with += (or the s = s + …​ pattern) on a string variable inside a loop body. The type of the target is confirmed to be string, so numeric accumulation is not flagged.

Rationale

Strings are immutable in .NET. Every += on a string allocates a new string and copies the existing characters into it, so concatenating inside a loop turns linear work into quadratic work and produces a large amount of short-lived garbage. A StringBuilder accumulates characters in a single growable buffer and appends in amortised constant time.

var s = "";
foreach (var item in items)
{
    s += item;          // FLAW — reallocates the whole string each iteration
}

int total = 0;
foreach (var n in numbers)
{
    total += n;         // OK — numeric accumulation, not a string
}

Remediation

Build the result with a StringBuilder and call ToString() once after the loop, or use string.Join / string.Concat when concatenating a known collection.

var sb = new StringBuilder();
foreach (var item in items)
{
    sb.Append(item);
}
var s = sb.ToString();

References