Tool to detect use/abuse of String.Concat (where StringBuilder should be used)

Posted by Mark Rushakoff on Stack Overflow See other posts from Stack Overflow or by Mark Rushakoff
Published on 2010-05-10T16:48:28Z Indexed on 2010/05/10 17:24 UTC
Read the original article Hit count: 243

Filed under:
|
|
|

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();
}

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.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET