Append to StringBuilder in C#

The Append() method in C# is used to add content to a StringBuilder object. Unlike strings, which are immutable, StringBuilder allows efficient concatenation of text without creating new string objects in memory.

StringBuilder is particularly useful when you need to perform multiple string concatenations, as it provides better performance than using the + operator repeatedly.

Syntax

Following is the syntax for creating a StringBuilder and using the Append() method −

StringBuilder sb = new StringBuilder();
sb.Append(value);

The Append() method can accept various data types including string, char, int, double, and others. It returns the same StringBuilder instance, enabling method chaining.

Using Append() with Method Chaining

Since Append() returns the same StringBuilder instance, you can chain multiple Append() calls together −

Example

using System;
using System.Text;

class Program {
   static void Main() {
      StringBuilder str = new StringBuilder();

      for (int j = 0; j 

The output of the above code is −

Result: 0 1 2 3 4 

Using Append() with Different Data Types

Example

using System;
using System.Text;

class Program {
   static void Main() {
      StringBuilder sb = new StringBuilder();
      
      sb.Append("Name: ");
      sb.Append("John");
      sb.Append(", Age: ");
      sb.Append(25);
      sb.Append(", Score: ");
      sb.Append(95.5);
      
      Console.WriteLine(sb.ToString());
   }
}

The output of the above code is −

Name: John, Age: 25, Score: 95.5

Using AppendLine() Method

The AppendLine() method appends text followed by a line terminator −

Example

using System;
using System.Text;

class Program {
   static void Main() {
      StringBuilder sb = new StringBuilder();
      
      sb.AppendLine("First line");
      sb.AppendLine("Second line");
      sb.Append("Third line without newline");
      
      Console.WriteLine(sb.ToString());
   }
}

The output of the above code is −

First line
Second line
Third line without newline

StringBuilder vs String Concatenation

StringBuilder String Concatenation
Mutable - modifies existing buffer Immutable - creates new string objects
Better performance for multiple concatenations Less efficient for multiple operations
Uses Append() method Uses + operator

Conclusion

The Append() method in StringBuilder provides an efficient way to concatenate strings and other data types. It supports method chaining and offers better performance than traditional string concatenation when dealing with multiple append operations.

Updated on: 2026-03-17T07:04:35+05:30

581 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements