CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder
Property | Value |
---|---|
Rule ID | CA1830 |
Title | Prefer strongly-typed Append and Insert method overloads on StringBuilder |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As suggestion |
Cause
An 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
Append and Insert provide overloads for multiple types beyond 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.
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.
#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.
[*.{cs,vb}]
dotnet_diagnostic.CA1830.severity = none
For more information, see How to suppress code analysis warnings.
See also
Phản hồi
https://aka.ms/ContentUserFeedback.
Sắp ra mắt: Trong năm 2024, chúng tôi sẽ dần gỡ bỏ Sự cố với GitHub dưới dạng cơ chế phản hồi cho nội dung và thay thế bằng hệ thống phản hồi mới. Để biết thêm thông tin, hãy xem:Gửi và xem ý kiến phản hồi dành cho