C#idiomatic C#
ca1830fundamentals/code-analysis/quality-rules

Code analysis

CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder

Learn about code analysis rule CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder

CA1830 Performance enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

An System.Text.StringBuilder Append or Insert method was called with an argument that was the result of calling ToString on a type for which the Append or Insert method has a dedicated overload.

Rule description

System.Text.StringBuilder.Append and System.Text.StringBuilder.Insert provide overloads for multiple types beyond System.String. When possible, prefer the strongly-typed overloads over using ToString() and the string-based overload.

How to fix violations

Delete the unnecessary ToString() from the invocation.

csharp
using System.Text;

class C
{
    int _value;

    // Violation
    public void Log(StringBuilder destination)
    {
        destination.Append("Value: ").Append(_value.ToString()).AppendLine();
    }

    // Fixed
    public void Log(StringBuilder destination)
    {
        destination.Append("Value: ").Append(_value).AppendLine();
    }
}

When to suppress warnings

It's safe to suppress a violation of this rule if you're not concerned about the performance impact from unnecessary string allocations.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA1830
// The code that's violating the rule is on this line.
#pragma warning restore CA1830

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA1830.severity = none

For more information, see How to suppress code analysis warnings.

See also