Back to Devexpress

Use String Builder

coderushforroslyn-115605-refactoring-assistance-use-string-builder.md

latest1.6 KB
Original Source

Use String Builder

  • Aug 03, 2020
  • 2 minutes to read

Purpose

Replaces string concatenation operations with the Append method calls on a local StringBuilder instance. The StringBuilder concatenates strings faster than the += operator.

Availability

Available when the cursor is on the declaration of a string variable, but only when that declaration is followed by several concatenation operations using the string.

Usage

  1. Place the caret on a string name in its declaration.

  2. Press the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions menu.

  3. Select Use StringBuilder from the menu.

After execution, the Refactoring replaces the concatenation operations with the string variable to the equivalent operations using a StringBuilder instance.

csharp
StringBuilder resultBuilder = new StringBuilder("Even numbers:");
for (int i = 1; i <= 5; i++) {
    resultBuilder.Append($" {i * 2}");
}
Console.WriteLine(resultBuilder.ToString());
vb
Dim resultBuilder As StringBuilder =
    New StringBuilder("Even numbers:")
For i As Integer = 1 To 5
    resultBuilder.Append($" {i * 2}")
Next i
Console.WriteLine(resultBuilder.ToString())

See Also

Use String.IsNullOrEmpty

Use String.Format

Use String.Compare

Split String