WiseTechGlobal / WTG.Analyzers

Analyzers from WiseTech Global to enforce our styles, behaviours, and prevent common mistakes.
Other
16 stars 3 forks source link

Warn against manipulating string values appended to a StringBuilder. #141

Closed brian-reichle closed 3 years ago

brian-reichle commented 3 years ago

Should add a rule to warn against the following patterns when appending to a StringBuilder, as they all create easily avoidable intermediate strings:

builder.Append(foo + "Suffix");
builder.Append(foo.Substring(3));
builder.Append(foo.Substring(5, 3));
builder.Append(string.Format("Prefix {0} Suffix", foo);
builder.Append($"Prefix {foo} Suffix");

The recommended replacements would be:

builder.Append(foo).Append("Suffix");
builder.Append(foo, 3, foo.Length - 3);
builder.Append(foo, 5, 3);
builder.AppendFormat("Prefix {0} Suffix", foo);
builder.AppendFormat("Prefix {0} Suffix", foo);

Similar warnings should be issued for other append methods.

yaakov-h commented 3 years ago

A fun edge case:

builder.Append(foo[3..5]) is safe if foo is a [ReadOnly]Span or [ReadOnly]Memory object as StringBuilder has appropriate overloads for that in modern .NET.

builder.Append(foo[3..5]) is not safe is foo is a string, as it will create a substring.