False positive on StringBuilder csharpsquid:S3063

Template for a good new topic, formatted with Markdown:

  • ALM used: Azure DevOps
  • CI system used: Azure DevOps
  • Scanner command used when applicable: SonarCloudAnalyze 3.4.3
  • Languages of the repository: C#, Typescript
  • Error observed (wrap logs/code around with triple quotes ``` for proper formatting)

Concatenating String + stringbuilder + string implicit calls ToString, SonarQube repots that ToString is not called. If it is used, another SonarQube issue is reported.

  • Steps to reproduce

Do not share screenshots of logs – share the text itself (bonus points for being well-formatted)!

        var observable = _provider.ConfirmationReplyObservable;
        _disposables.Add(observable.Subscribe(x =>
        {
            // Synchronize to GUI thread!
            Application.Current.Dispatcher.Invoke((Action)delegate
            {
                string errorMessage = string.IsNullOrEmpty(x.ErrorMessage) ? "Emtpy" : x.ErrorMessage;
                StringBuilder stringBuilder = new(); // this emnits S3063 Remove this "StringBuilder"; ".ToString()" is never called.
Remove this "StringBuilder"; ".ToString()" is never called.

                stringBuilder.Append(CultureInfo.InvariantCulture, $"Id: {x.NotificationId} Result: {x.Result} Error message: {errorMessage};");
                foreach (ControlReply controlReply in x.ControlReply)
                {
                    if (controlReply.EditString is not null)
                    {
                        stringBuilder.Append(CultureInfo.InvariantCulture, $" EditString: {controlReply.EditString.Value};");
                    }
                    else if (controlReply.EditValue is not null)
                    {
                        stringBuilder.Append(CultureInfo.InvariantCulture, $" EditValue: {controlReply.EditValue.Value};");
                    }
                    else if (controlReply.CheckBox is not null)
                    {
                        stringBuilder.Append(CultureInfo.InvariantCulture, $" CheckBox: {controlReply.CheckBox.Value};");
                    }
                    else if (controlReply.ComboBox is not null)
                    {
                        stringBuilder.Append(CultureInfo.InvariantCulture, $" ComboBox: {controlReply.ComboBox.Value};");
                    }
                }
                ConfirmationReplies = ConfirmationReplies + stringBuilder + Environment.NewLine; // if used stringBuilder.ToString(): S1858 There's no need to call 'ToString()', the compiler will do it for you.
            });
        }));

Nice catch!

The reproducer can be a bit shorter though:

static string Log()
{
    var sb = new StringBuilder();
    sb.Append(42);
    return sb + Environment.NewLine;
}
1 Like