0
0
C Sharp (C#)programming~5 mins

StringBuilder and why it exists in C Sharp (C#)

Choose your learning style9 modes available
Introduction

StringBuilder helps you build or change text efficiently without making many copies. It saves time and memory when you change text a lot.

When you need to join many pieces of text together, like building a sentence from words.
When you want to change text many times, like adding or removing parts in a loop.
When performance matters and you want your program to run faster with text changes.
When you want to avoid creating many temporary text copies that slow down your program.
Syntax
C Sharp (C#)
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
sb.Append(" World");
string result = sb.ToString();

Use Append to add text to the StringBuilder.

Use ToString() to get the final text after all changes.

Examples
This creates a message "Hi there!" by adding two parts.
C Sharp (C#)
StringBuilder sb = new StringBuilder();
sb.Append("Hi");
sb.Append(" there!");
string message = sb.ToString();
You can start with some text inside the StringBuilder.
C Sharp (C#)
StringBuilder sb = new StringBuilder("Start");
sb.Append(" and continue");
string text = sb.ToString();
This adds numbers 0, 1, 2 to the text efficiently inside a loop.
C Sharp (C#)
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
    sb.Append(i);
}
string numbers = sb.ToString();
Sample Program

This program builds the text "Hello, world!" step by step using StringBuilder, then prints it.

C Sharp (C#)
using System;
using System.Text;

class Program {
    static void Main() {
        StringBuilder sb = new StringBuilder();
        sb.Append("Hello");
        sb.Append(", ");
        sb.Append("world");
        sb.Append("!");
        string result = sb.ToString();
        Console.WriteLine(result);
    }
}
OutputSuccess
Important Notes

Strings in C# are immutable, meaning they cannot change once created. StringBuilder helps avoid making many copies.

Use StringBuilder when you expect many changes to text, otherwise simple string concatenation is fine.

Summary

StringBuilder helps build or change text efficiently.

It avoids creating many copies of strings, saving memory and time.

Use it when you add or change text many times, especially in loops.