All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S3063.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

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

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

public void DoSomething(List<string> strings) {
  foreach(var str in strings) {
    // ...
  }
}

or

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.




© 2015 - 2024 Weber Informatics LLC | Privacy Policy