Skip to main content

Use String Builder

  • 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.

    Note

    The blinking cursor shows the caret’s position at which the Refactoring is available.

    string result = "Even numbers:";
    for (int i = 1; i <= 5; i++) {
        result += $" {i * 2}";
    }
    Console.WriteLine(result);
    
  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.

StringBuilder resultBuilder = new StringBuilder("Even numbers:");
for (int i = 1; i <= 5; i++) {
    resultBuilder.Append($" {i * 2}");
}
Console.WriteLine(resultBuilder.ToString());
See Also