2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-02-15 13:07:42 +01:00
`StringBuilder` instances that never build a `string` clutter the code and worse are a drag on performance. Either they should be removed, or the missing `ToString()` call should be added.
2021-06-02 20:44:38 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-09-20 15:38:42 +02:00
2023-02-15 13:07:42 +01:00
[source,csharp]
----
public void DoSomething(List<string> strings) {
var sb = new StringBuilder(); // Noncompliant
sb.Append("Got: ");
foreach(var str in strings) {
sb.Append(str).Append(", ");
// ...
}
}
----
2021-09-20 15:38:42 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-09-20 15:38:42 +02:00
2023-02-15 13:07:42 +01:00
[source,csharp]
----
public void DoSomething(List<string> strings) {
foreach(var str in strings) {
// ...
}
}
----
or
[source,csharp]
----
public void DoSomething(List<string> strings) {
var sb = new StringBuilder();
sb.Append("Got: ");
foreach(var str in strings) {
sb.Append(str).Append(", ");
// ...
}
logger.LogInformation(sb.ToString());
}
----
2021-06-02 20:44:38 +02:00
2023-05-03 11:06:20 +02:00
=== Exceptions
2023-02-15 13:07:42 +01:00
No issue is reported when `StringBuilder` is:
* Accessed through `sb.CopyTo()`, `sb.GetChunks()`, `sb.Length`, or `sb[index]`.
* Passed as a method argument, on the grounds that it will likely be accessed through a `ToString()` invocation there.
* Passed in as a parameter to the current method, on the grounds that the callee will materialize the string.
* Retrieved by a custom function (`var sb = GetStringBuilder();`).
2023-05-25 14:18:12 +02:00
* Returned by the method.