Use StringBuilder.Append(char) for single character strings
Use StringBuilder.Append(char) for single character strings
Microsoft docsDescription
When calling StringBuilder.Append with a unit length string, consider using a const char rather than a unit length const string to improve performance.
Cause
This rule fires when a unit length string is passed to the System.Text.StringBuilder.Append method.
How to fix violations
The violation can either be fixed manually, or, in some cases, using Quick Actions to fix code in Visual Studio. Examples:
### Example 1
Invocations of StringBuilder.Append with a string literal of unit length: A code fix is available for this rule in Visual Studio. To use it, position the cursor on the violation and press <kbd>Ctrl</kbd>+<kbd>.</kbd> (period). Choose Consider using 'StringBuilder.Append(char)' when applicable. from the list of options that is presented. !Code fix for CA1834 - Use StringBuilder.Append(char) for single character strings
Fix applied by Visual Studio:
In some cases, for example when using a unit length const string class field, a code-fix is not suggested by Visual Studio (but the analyzer still fires). These instances require a manual fix.
### Example 2
Invocations of StringBuilder.Append with a const string class field of unit length:
After careful analysis, unitString here can be changed to a char without causing any build errors.
Example
using System;
using System.Text;
namespace TestNamespace
{
class TestClass
{
private void TestMethod()
{
StringBuilder sb = new StringBuilder();
sb.Append("a");
}
}
}When to suppress
It's safe to suppress a violation of this rule if you're not concerned about improving performance when using StringBuilder.