It's common knowledge that you shouldn't use a StringBuilder in place of a small number of concatenations:
string s = "Hello";
if (greetingWorld)
{
s += " World";
}
s += "!";
However, in loops of a significant size, StringBuilder is the obvious choice:
string s = "";
foreach (var i in Enumerable.Range(1,5000))
{
s += i.ToString(); // <- bad idea!
}
Console.WriteLine(s);
Is there a tool that I can run on either raw C# source or a compiled assembly to identify where in the source code that String.Concat
is being called? (If you're not familiar, s += "foo"
is mapped to String.Concat
in the IL output.) Obviously, I can't realistically search through an entire project and evaluate every +=
to identify whether the lvalue is a string.
Ideally, it would only point out calls inside a for/foreach loop, but I would even put up with all the false positives of noting every String.Concat
. Also, I'm aware that there are some refactoring tools that will automatically refactor my code to use StringBuilder
, but I am only interested in identifying the Concat
usage at this point.
I routinely run Gendarme and FxCop on my code, and neither of those tools identify what I've described. However, as @Cristian pointed out, older versions of FxCop used to check for this. Maybe there's a way to extract just that rule from an old version of FxCop and tell the newer version (1.36) to use it?