rspec/rules/S3063/csharp/rule.adoc
github-actions[bot] a8b5a83add
Create rule S3063: Add vbnet language (#1524)
* Add vbnet to rule S3063

* Add adoc for CS/VB

* Add exceptions

* Add invocations exceptions

* Addressed PR comments

* Semplifications, better wording on the descriptions

* Small description fix

* Add indexer and .Length expression exceptions and fix description

* sub-list to inline

* Fix typos

---------

Co-authored-by: cristian-ambrosini-sonarsource <cristian-ambrosini-sonarsource@users.noreply.github.com>
Co-authored-by: Cristian Ambrosini <cristian.ambrosini@sonarsource.com>
2023-02-15 13:07:42 +01:00

49 lines
1.3 KiB
Plaintext

`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.
== Noncompliant Code Example
[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(", ");
// ...
}
}
----
== Compliant Solution
[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());
}
----
== Exceptions
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();`).
* Returned by the method.